babylon.max.js 3.9 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035510365103751038510395104051041510425104351044510455104651047510485104951050510515105251053510545105551056510575105851059510605106151062510635106451065510665106751068510695107051071510725107351074510755107651077510785107951080510815108251083510845108551086510875108851089510905109151092510935109451095510965109751098510995110051101511025110351104511055110651107511085110951110511115111251113511145111551116511175111851119511205112151122511235112451125511265112751128511295113051131511325113351134511355113651137511385113951140511415114251143511445114551146511475114851149511505115151152511535115451155511565115751158511595116051161511625116351164511655116651167511685116951170511715117251173511745117551176511775117851179511805118151182511835118451185511865118751188511895119051191511925119351194511955119651197511985119951200512015120251203512045120551206512075120851209512105121151212512135121451215512165121751218512195122051221512225122351224512255122651227512285122951230512315123251233512345123551236512375123851239512405124151242512435124451245512465124751248512495125051251512525125351254512555125651257512585125951260512615126251263512645126551266512675126851269512705127151272512735127451275512765127751278512795128051281512825128351284512855128651287512885128951290512915129251293512945129551296512975129851299513005130151302513035130451305513065130751308513095131051311513125131351314513155131651317513185131951320513215132251323513245132551326513275132851329513305133151332513335133451335513365133751338513395134051341513425134351344513455134651347513485134951350513515135251353513545135551356513575135851359513605136151362513635136451365513665136751368513695137051371513725137351374513755137651377513785137951380513815138251383513845138551386513875138851389513905139151392513935139451395513965139751398513995140051401514025140351404514055140651407514085140951410514115141251413514145141551416514175141851419514205142151422514235142451425514265142751428514295143051431514325143351434514355143651437514385143951440514415144251443514445144551446514475144851449514505145151452514535145451455514565145751458514595146051461514625146351464514655146651467514685146951470514715147251473514745147551476514775147851479514805148151482514835148451485514865148751488514895149051491514925149351494514955149651497514985149951500515015150251503515045150551506515075150851509515105151151512515135151451515515165151751518515195152051521515225152351524515255152651527515285152951530515315153251533515345153551536515375153851539515405154151542515435154451545515465154751548515495155051551515525155351554515555155651557515585155951560515615156251563515645156551566515675156851569515705157151572515735157451575515765157751578515795158051581515825158351584515855158651587515885158951590515915159251593515945159551596515975159851599516005160151602516035160451605516065160751608516095161051611516125161351614516155161651617516185161951620516215162251623516245162551626516275162851629516305163151632516335163451635516365163751638516395164051641516425164351644516455164651647516485164951650516515165251653516545165551656516575165851659516605166151662516635166451665516665166751668516695167051671516725167351674516755167651677516785167951680516815168251683516845168551686516875168851689516905169151692516935169451695516965169751698516995170051701517025170351704517055170651707517085170951710517115171251713517145171551716517175171851719517205172151722517235172451725517265172751728517295173051731517325173351734517355173651737517385173951740517415174251743517445174551746517475174851749517505175151752517535175451755517565175751758517595176051761517625176351764517655176651767517685176951770517715177251773517745177551776517775177851779517805178151782517835178451785517865178751788517895179051791517925179351794517955179651797517985179951800518015180251803518045180551806518075180851809518105181151812518135181451815518165181751818518195182051821518225182351824518255182651827518285182951830518315183251833518345183551836518375183851839518405184151842518435184451845518465184751848518495185051851518525185351854518555185651857518585185951860518615186251863518645186551866518675186851869518705187151872518735187451875518765187751878518795188051881518825188351884518855188651887518885188951890518915189251893518945189551896518975189851899519005190151902519035190451905519065190751908519095191051911519125191351914519155191651917519185191951920519215192251923519245192551926519275192851929519305193151932519335193451935519365193751938519395194051941519425194351944519455194651947519485194951950519515195251953519545195551956519575195851959519605196151962519635196451965519665196751968519695197051971519725197351974519755197651977519785197951980519815198251983519845198551986519875198851989519905199151992519935199451995519965199751998519995200052001520025200352004520055200652007520085200952010520115201252013520145201552016520175201852019520205202152022520235202452025520265202752028520295203052031520325203352034520355203652037520385203952040520415204252043520445204552046520475204852049520505205152052520535205452055520565205752058520595206052061520625206352064520655206652067520685206952070520715207252073520745207552076520775207852079520805208152082520835208452085520865208752088520895209052091520925209352094520955209652097520985209952100521015210252103521045210552106521075210852109521105211152112521135211452115521165211752118521195212052121521225212352124521255212652127521285212952130521315213252133521345213552136521375213852139521405214152142521435214452145521465214752148521495215052151521525215352154521555215652157521585215952160521615216252163521645216552166521675216852169521705217152172521735217452175521765217752178521795218052181521825218352184521855218652187521885218952190521915219252193521945219552196521975219852199522005220152202522035220452205522065220752208522095221052211522125221352214522155221652217522185221952220522215222252223522245222552226522275222852229522305223152232522335223452235522365223752238522395224052241522425224352244522455224652247522485224952250522515225252253522545225552256522575225852259522605226152262522635226452265522665226752268522695227052271522725227352274522755227652277522785227952280522815228252283522845228552286522875228852289522905229152292522935229452295522965229752298522995230052301523025230352304523055230652307523085230952310523115231252313523145231552316523175231852319523205232152322523235232452325523265232752328523295233052331523325233352334523355233652337523385233952340523415234252343523445234552346523475234852349523505235152352523535235452355523565235752358523595236052361523625236352364523655236652367523685236952370523715237252373523745237552376523775237852379523805238152382523835238452385523865238752388523895239052391523925239352394523955239652397523985239952400524015240252403524045240552406524075240852409524105241152412524135241452415524165241752418524195242052421524225242352424524255242652427524285242952430524315243252433524345243552436524375243852439524405244152442524435244452445524465244752448524495245052451524525245352454524555245652457524585245952460524615246252463524645246552466524675246852469524705247152472524735247452475524765247752478524795248052481524825248352484524855248652487524885248952490524915249252493524945249552496524975249852499525005250152502525035250452505525065250752508525095251052511525125251352514525155251652517525185251952520525215252252523525245252552526525275252852529525305253152532525335253452535525365253752538525395254052541525425254352544525455254652547525485254952550525515255252553525545255552556525575255852559525605256152562525635256452565525665256752568525695257052571525725257352574525755257652577525785257952580525815258252583525845258552586525875258852589525905259152592525935259452595525965259752598525995260052601526025260352604526055260652607526085260952610526115261252613526145261552616526175261852619526205262152622526235262452625526265262752628526295263052631526325263352634526355263652637526385263952640526415264252643526445264552646526475264852649526505265152652526535265452655526565265752658526595266052661526625266352664526655266652667526685266952670526715267252673526745267552676526775267852679526805268152682526835268452685526865268752688526895269052691526925269352694526955269652697526985269952700527015270252703527045270552706527075270852709527105271152712527135271452715527165271752718527195272052721527225272352724527255272652727527285272952730527315273252733527345273552736527375273852739527405274152742527435274452745527465274752748527495275052751527525275352754527555275652757527585275952760527615276252763527645276552766527675276852769527705277152772527735277452775527765277752778527795278052781527825278352784527855278652787527885278952790527915279252793527945279552796527975279852799528005280152802528035280452805528065280752808528095281052811528125281352814528155281652817528185281952820528215282252823528245282552826528275282852829528305283152832528335283452835528365283752838528395284052841528425284352844528455284652847528485284952850528515285252853528545285552856528575285852859528605286152862528635286452865528665286752868528695287052871528725287352874528755287652877528785287952880528815288252883528845288552886528875288852889528905289152892528935289452895528965289752898528995290052901529025290352904529055290652907529085290952910529115291252913529145291552916529175291852919529205292152922529235292452925529265292752928529295293052931529325293352934529355293652937529385293952940529415294252943529445294552946529475294852949529505295152952529535295452955529565295752958529595296052961529625296352964529655296652967529685296952970529715297252973529745297552976529775297852979529805298152982529835298452985529865298752988529895299052991529925299352994529955299652997529985299953000530015300253003530045300553006530075300853009530105301153012530135301453015530165301753018530195302053021530225302353024530255302653027530285302953030530315303253033530345303553036530375303853039530405304153042530435304453045530465304753048530495305053051530525305353054530555305653057530585305953060530615306253063530645306553066530675306853069530705307153072530735307453075530765307753078530795308053081530825308353084530855308653087530885308953090530915309253093530945309553096530975309853099531005310153102531035310453105531065310753108531095311053111531125311353114531155311653117531185311953120531215312253123531245312553126531275312853129531305313153132531335313453135531365313753138531395314053141531425314353144531455314653147531485314953150531515315253153531545315553156531575315853159531605316153162531635316453165531665316753168531695317053171531725317353174531755317653177531785317953180531815318253183531845318553186531875318853189531905319153192531935319453195531965319753198531995320053201532025320353204532055320653207532085320953210532115321253213532145321553216532175321853219532205322153222532235322453225532265322753228532295323053231532325323353234532355323653237532385323953240532415324253243532445324553246532475324853249532505325153252532535325453255532565325753258532595326053261532625326353264532655326653267532685326953270532715327253273532745327553276532775327853279532805328153282532835328453285532865328753288532895329053291532925329353294532955329653297532985329953300533015330253303533045330553306533075330853309533105331153312533135331453315533165331753318533195332053321533225332353324533255332653327533285332953330533315333253333533345333553336533375333853339533405334153342533435334453345533465334753348533495335053351533525335353354533555335653357533585335953360533615336253363533645336553366533675336853369533705337153372533735337453375533765337753378533795338053381533825338353384533855338653387533885338953390533915339253393533945339553396533975339853399534005340153402534035340453405534065340753408534095341053411534125341353414534155341653417534185341953420534215342253423534245342553426534275342853429534305343153432534335343453435534365343753438534395344053441534425344353444534455344653447534485344953450534515345253453534545345553456534575345853459534605346153462534635346453465534665346753468534695347053471534725347353474534755347653477534785347953480534815348253483534845348553486534875348853489534905349153492534935349453495534965349753498534995350053501535025350353504535055350653507535085350953510535115351253513535145351553516535175351853519535205352153522535235352453525535265352753528535295353053531535325353353534535355353653537535385353953540535415354253543535445354553546535475354853549535505355153552535535355453555535565355753558535595356053561535625356353564535655356653567535685356953570535715357253573535745357553576535775357853579535805358153582535835358453585535865358753588535895359053591535925359353594535955359653597535985359953600536015360253603536045360553606536075360853609536105361153612536135361453615536165361753618536195362053621536225362353624536255362653627536285362953630536315363253633536345363553636536375363853639536405364153642536435364453645536465364753648536495365053651536525365353654536555365653657536585365953660536615366253663536645366553666536675366853669536705367153672536735367453675536765367753678536795368053681536825368353684536855368653687536885368953690536915369253693536945369553696536975369853699537005370153702537035370453705537065370753708537095371053711537125371353714537155371653717537185371953720537215372253723537245372553726537275372853729537305373153732537335373453735537365373753738537395374053741537425374353744537455374653747537485374953750537515375253753537545375553756537575375853759537605376153762537635376453765537665376753768537695377053771537725377353774537755377653777537785377953780537815378253783537845378553786537875378853789537905379153792537935379453795537965379753798537995380053801538025380353804538055380653807538085380953810538115381253813538145381553816538175381853819538205382153822538235382453825538265382753828538295383053831538325383353834538355383653837538385383953840538415384253843538445384553846538475384853849538505385153852538535385453855538565385753858538595386053861538625386353864538655386653867538685386953870538715387253873538745387553876538775387853879538805388153882538835388453885538865388753888538895389053891538925389353894538955389653897538985389953900539015390253903539045390553906539075390853909539105391153912539135391453915539165391753918539195392053921539225392353924539255392653927539285392953930539315393253933539345393553936539375393853939539405394153942539435394453945539465394753948539495395053951539525395353954539555395653957539585395953960539615396253963539645396553966539675396853969539705397153972539735397453975539765397753978539795398053981539825398353984539855398653987539885398953990539915399253993539945399553996539975399853999540005400154002540035400454005540065400754008540095401054011540125401354014540155401654017540185401954020540215402254023540245402554026540275402854029540305403154032540335403454035540365403754038540395404054041540425404354044540455404654047540485404954050540515405254053540545405554056540575405854059540605406154062540635406454065540665406754068540695407054071540725407354074540755407654077540785407954080540815408254083540845408554086540875408854089540905409154092540935409454095540965409754098540995410054101541025410354104541055410654107541085410954110541115411254113541145411554116541175411854119541205412154122541235412454125541265412754128541295413054131541325413354134541355413654137541385413954140541415414254143541445414554146541475414854149541505415154152541535415454155541565415754158541595416054161541625416354164541655416654167541685416954170541715417254173541745417554176541775417854179541805418154182541835418454185541865418754188541895419054191541925419354194541955419654197541985419954200542015420254203542045420554206542075420854209542105421154212542135421454215542165421754218542195422054221542225422354224542255422654227542285422954230542315423254233542345423554236542375423854239542405424154242542435424454245542465424754248542495425054251542525425354254542555425654257542585425954260542615426254263542645426554266542675426854269542705427154272542735427454275542765427754278542795428054281542825428354284542855428654287542885428954290542915429254293542945429554296542975429854299543005430154302543035430454305543065430754308543095431054311543125431354314543155431654317543185431954320543215432254323543245432554326543275432854329543305433154332543335433454335543365433754338543395434054341543425434354344543455434654347543485434954350543515435254353543545435554356543575435854359543605436154362543635436454365543665436754368543695437054371543725437354374543755437654377543785437954380543815438254383543845438554386543875438854389543905439154392543935439454395543965439754398543995440054401544025440354404544055440654407544085440954410544115441254413544145441554416544175441854419544205442154422544235442454425544265442754428544295443054431544325443354434544355443654437544385443954440544415444254443544445444554446544475444854449544505445154452544535445454455544565445754458544595446054461544625446354464544655446654467544685446954470544715447254473544745447554476544775447854479544805448154482544835448454485544865448754488544895449054491544925449354494544955449654497544985449954500545015450254503545045450554506545075450854509545105451154512545135451454515545165451754518545195452054521545225452354524545255452654527545285452954530545315453254533545345453554536545375453854539545405454154542545435454454545545465454754548545495455054551545525455354554545555455654557545585455954560545615456254563545645456554566545675456854569545705457154572545735457454575545765457754578545795458054581545825458354584545855458654587545885458954590545915459254593545945459554596545975459854599546005460154602546035460454605546065460754608546095461054611546125461354614546155461654617546185461954620546215462254623546245462554626546275462854629546305463154632546335463454635546365463754638546395464054641546425464354644546455464654647546485464954650546515465254653546545465554656546575465854659546605466154662546635466454665546665466754668546695467054671546725467354674546755467654677546785467954680546815468254683546845468554686546875468854689546905469154692546935469454695546965469754698546995470054701547025470354704547055470654707547085470954710547115471254713547145471554716547175471854719547205472154722547235472454725547265472754728547295473054731547325473354734547355473654737547385473954740547415474254743547445474554746547475474854749547505475154752547535475454755547565475754758547595476054761547625476354764547655476654767547685476954770547715477254773547745477554776547775477854779547805478154782547835478454785547865478754788547895479054791547925479354794547955479654797547985479954800548015480254803548045480554806548075480854809548105481154812548135481454815548165481754818548195482054821548225482354824548255482654827548285482954830548315483254833548345483554836548375483854839548405484154842548435484454845548465484754848548495485054851548525485354854548555485654857548585485954860548615486254863548645486554866548675486854869548705487154872548735487454875548765487754878548795488054881548825488354884548855488654887548885488954890548915489254893548945489554896548975489854899549005490154902549035490454905549065490754908549095491054911549125491354914549155491654917549185491954920549215492254923549245492554926549275492854929549305493154932549335493454935549365493754938549395494054941549425494354944549455494654947549485494954950549515495254953549545495554956549575495854959549605496154962549635496454965549665496754968549695497054971549725497354974549755497654977549785497954980549815498254983549845498554986549875498854989549905499154992549935499454995549965499754998549995500055001550025500355004550055500655007550085500955010550115501255013550145501555016550175501855019550205502155022550235502455025550265502755028550295503055031550325503355034550355503655037550385503955040550415504255043550445504555046550475504855049550505505155052550535505455055550565505755058550595506055061550625506355064550655506655067550685506955070550715507255073550745507555076550775507855079550805508155082550835508455085550865508755088550895509055091550925509355094550955509655097550985509955100551015510255103551045510555106551075510855109551105511155112551135511455115551165511755118551195512055121551225512355124551255512655127551285512955130551315513255133551345513555136551375513855139551405514155142551435514455145551465514755148551495515055151551525515355154551555515655157551585515955160551615516255163551645516555166551675516855169551705517155172551735517455175551765517755178551795518055181551825518355184551855518655187551885518955190551915519255193551945519555196551975519855199552005520155202552035520455205552065520755208552095521055211552125521355214552155521655217552185521955220552215522255223552245522555226552275522855229552305523155232552335523455235552365523755238552395524055241552425524355244552455524655247552485524955250552515525255253552545525555256552575525855259552605526155262552635526455265552665526755268552695527055271552725527355274552755527655277552785527955280552815528255283552845528555286552875528855289552905529155292552935529455295552965529755298552995530055301553025530355304553055530655307553085530955310553115531255313553145531555316553175531855319553205532155322553235532455325553265532755328553295533055331553325533355334553355533655337553385533955340553415534255343553445534555346553475534855349553505535155352553535535455355553565535755358553595536055361553625536355364553655536655367553685536955370553715537255373553745537555376553775537855379553805538155382553835538455385553865538755388553895539055391553925539355394553955539655397553985539955400554015540255403554045540555406554075540855409554105541155412554135541455415554165541755418554195542055421554225542355424554255542655427554285542955430554315543255433554345543555436554375543855439554405544155442554435544455445554465544755448554495545055451554525545355454554555545655457554585545955460554615546255463554645546555466554675546855469554705547155472554735547455475554765547755478554795548055481554825548355484554855548655487554885548955490554915549255493554945549555496554975549855499555005550155502555035550455505555065550755508555095551055511555125551355514555155551655517555185551955520555215552255523555245552555526555275552855529555305553155532555335553455535555365553755538555395554055541555425554355544555455554655547555485554955550555515555255553555545555555556555575555855559555605556155562555635556455565555665556755568555695557055571555725557355574555755557655577555785557955580555815558255583555845558555586555875558855589555905559155592555935559455595555965559755598555995560055601556025560355604556055560655607556085560955610556115561255613556145561555616556175561855619556205562155622556235562455625556265562755628556295563055631556325563355634556355563655637556385563955640556415564255643556445564555646556475564855649556505565155652556535565455655556565565755658556595566055661556625566355664556655566655667556685566955670556715567255673556745567555676556775567855679556805568155682556835568455685556865568755688556895569055691556925569355694556955569655697556985569955700557015570255703557045570555706557075570855709557105571155712557135571455715557165571755718557195572055721557225572355724557255572655727557285572955730557315573255733557345573555736557375573855739557405574155742557435574455745557465574755748557495575055751557525575355754557555575655757557585575955760557615576255763557645576555766557675576855769557705577155772557735577455775557765577755778557795578055781557825578355784557855578655787557885578955790557915579255793557945579555796557975579855799558005580155802558035580455805558065580755808558095581055811558125581355814558155581655817558185581955820558215582255823558245582555826558275582855829558305583155832558335583455835558365583755838558395584055841558425584355844558455584655847558485584955850558515585255853558545585555856558575585855859558605586155862558635586455865558665586755868558695587055871558725587355874558755587655877558785587955880558815588255883558845588555886558875588855889558905589155892558935589455895558965589755898558995590055901559025590355904559055590655907559085590955910559115591255913559145591555916559175591855919559205592155922559235592455925559265592755928559295593055931559325593355934559355593655937559385593955940559415594255943559445594555946559475594855949559505595155952559535595455955559565595755958559595596055961559625596355964559655596655967559685596955970559715597255973559745597555976559775597855979559805598155982559835598455985559865598755988559895599055991559925599355994559955599655997559985599956000560015600256003560045600556006560075600856009560105601156012560135601456015560165601756018560195602056021560225602356024560255602656027560285602956030560315603256033560345603556036560375603856039560405604156042560435604456045560465604756048560495605056051560525605356054560555605656057560585605956060560615606256063560645606556066560675606856069560705607156072560735607456075560765607756078560795608056081560825608356084560855608656087560885608956090560915609256093560945609556096560975609856099561005610156102561035610456105561065610756108561095611056111561125611356114561155611656117561185611956120561215612256123561245612556126561275612856129561305613156132561335613456135561365613756138561395614056141561425614356144561455614656147561485614956150561515615256153561545615556156561575615856159561605616156162561635616456165561665616756168561695617056171561725617356174561755617656177561785617956180561815618256183561845618556186561875618856189561905619156192561935619456195561965619756198561995620056201562025620356204562055620656207562085620956210562115621256213562145621556216562175621856219562205622156222562235622456225562265622756228562295623056231562325623356234562355623656237562385623956240562415624256243562445624556246562475624856249562505625156252562535625456255562565625756258562595626056261562625626356264562655626656267562685626956270562715627256273562745627556276562775627856279562805628156282562835628456285562865628756288562895629056291562925629356294562955629656297562985629956300563015630256303563045630556306563075630856309563105631156312563135631456315563165631756318563195632056321563225632356324563255632656327563285632956330563315633256333563345633556336563375633856339563405634156342563435634456345563465634756348563495635056351563525635356354563555635656357563585635956360563615636256363563645636556366563675636856369563705637156372563735637456375563765637756378563795638056381563825638356384563855638656387563885638956390563915639256393563945639556396563975639856399564005640156402564035640456405564065640756408564095641056411564125641356414564155641656417564185641956420564215642256423564245642556426564275642856429564305643156432564335643456435564365643756438564395644056441564425644356444564455644656447564485644956450564515645256453564545645556456564575645856459564605646156462564635646456465564665646756468564695647056471564725647356474564755647656477564785647956480564815648256483564845648556486564875648856489564905649156492564935649456495564965649756498564995650056501565025650356504565055650656507565085650956510565115651256513565145651556516565175651856519565205652156522565235652456525565265652756528565295653056531565325653356534565355653656537565385653956540565415654256543565445654556546565475654856549565505655156552565535655456555565565655756558565595656056561565625656356564565655656656567565685656956570565715657256573565745657556576565775657856579565805658156582565835658456585565865658756588565895659056591565925659356594565955659656597565985659956600566015660256603566045660556606566075660856609566105661156612566135661456615566165661756618566195662056621566225662356624566255662656627566285662956630566315663256633566345663556636566375663856639566405664156642566435664456645566465664756648566495665056651566525665356654566555665656657566585665956660566615666256663566645666556666566675666856669566705667156672566735667456675566765667756678566795668056681566825668356684566855668656687566885668956690566915669256693566945669556696566975669856699567005670156702567035670456705567065670756708567095671056711567125671356714567155671656717567185671956720567215672256723567245672556726567275672856729567305673156732567335673456735567365673756738567395674056741567425674356744567455674656747567485674956750567515675256753567545675556756567575675856759567605676156762567635676456765567665676756768567695677056771567725677356774567755677656777567785677956780567815678256783567845678556786567875678856789567905679156792567935679456795567965679756798567995680056801568025680356804568055680656807568085680956810568115681256813568145681556816568175681856819568205682156822568235682456825568265682756828568295683056831568325683356834568355683656837568385683956840568415684256843568445684556846568475684856849568505685156852568535685456855568565685756858568595686056861568625686356864568655686656867568685686956870568715687256873568745687556876568775687856879568805688156882568835688456885568865688756888568895689056891568925689356894568955689656897568985689956900569015690256903569045690556906569075690856909569105691156912569135691456915569165691756918569195692056921569225692356924569255692656927569285692956930569315693256933569345693556936569375693856939569405694156942569435694456945569465694756948569495695056951569525695356954569555695656957569585695956960569615696256963569645696556966569675696856969569705697156972569735697456975569765697756978569795698056981569825698356984569855698656987569885698956990569915699256993569945699556996569975699856999570005700157002570035700457005570065700757008570095701057011570125701357014570155701657017570185701957020570215702257023570245702557026570275702857029570305703157032570335703457035570365703757038570395704057041570425704357044570455704657047570485704957050570515705257053570545705557056570575705857059570605706157062570635706457065570665706757068570695707057071570725707357074570755707657077570785707957080570815708257083570845708557086570875708857089570905709157092570935709457095570965709757098570995710057101571025710357104571055710657107571085710957110571115711257113571145711557116571175711857119571205712157122571235712457125571265712757128571295713057131571325713357134571355713657137571385713957140571415714257143571445714557146571475714857149571505715157152571535715457155571565715757158571595716057161571625716357164571655716657167571685716957170571715717257173571745717557176571775717857179571805718157182571835718457185571865718757188571895719057191571925719357194571955719657197571985719957200572015720257203572045720557206572075720857209572105721157212572135721457215572165721757218572195722057221572225722357224572255722657227572285722957230572315723257233572345723557236572375723857239572405724157242572435724457245572465724757248572495725057251572525725357254572555725657257572585725957260572615726257263572645726557266572675726857269572705727157272572735727457275572765727757278572795728057281572825728357284572855728657287572885728957290572915729257293572945729557296572975729857299573005730157302573035730457305573065730757308573095731057311573125731357314573155731657317573185731957320573215732257323573245732557326573275732857329573305733157332573335733457335573365733757338573395734057341573425734357344573455734657347573485734957350573515735257353573545735557356573575735857359573605736157362573635736457365573665736757368573695737057371573725737357374573755737657377573785737957380573815738257383573845738557386573875738857389573905739157392573935739457395573965739757398573995740057401574025740357404574055740657407574085740957410574115741257413574145741557416574175741857419574205742157422574235742457425574265742757428574295743057431574325743357434574355743657437574385743957440574415744257443574445744557446574475744857449574505745157452574535745457455574565745757458574595746057461574625746357464574655746657467574685746957470574715747257473574745747557476574775747857479574805748157482574835748457485574865748757488574895749057491574925749357494574955749657497574985749957500575015750257503575045750557506575075750857509575105751157512575135751457515575165751757518575195752057521575225752357524575255752657527575285752957530575315753257533575345753557536575375753857539575405754157542575435754457545575465754757548575495755057551575525755357554575555755657557575585755957560575615756257563575645756557566575675756857569575705757157572575735757457575575765757757578575795758057581575825758357584575855758657587575885758957590575915759257593575945759557596575975759857599576005760157602576035760457605576065760757608576095761057611576125761357614576155761657617576185761957620576215762257623576245762557626576275762857629576305763157632576335763457635576365763757638576395764057641576425764357644576455764657647576485764957650576515765257653576545765557656576575765857659576605766157662576635766457665576665766757668576695767057671576725767357674576755767657677576785767957680576815768257683576845768557686576875768857689576905769157692576935769457695576965769757698576995770057701577025770357704577055770657707577085770957710577115771257713577145771557716577175771857719577205772157722577235772457725577265772757728577295773057731577325773357734577355773657737577385773957740577415774257743577445774557746577475774857749577505775157752577535775457755577565775757758577595776057761577625776357764577655776657767577685776957770577715777257773577745777557776577775777857779577805778157782577835778457785577865778757788577895779057791577925779357794577955779657797577985779957800578015780257803578045780557806578075780857809578105781157812578135781457815578165781757818578195782057821578225782357824578255782657827578285782957830578315783257833578345783557836578375783857839578405784157842578435784457845578465784757848578495785057851578525785357854578555785657857578585785957860578615786257863578645786557866578675786857869578705787157872578735787457875578765787757878578795788057881578825788357884578855788657887578885788957890578915789257893578945789557896578975789857899579005790157902579035790457905579065790757908579095791057911579125791357914579155791657917579185791957920579215792257923579245792557926579275792857929579305793157932579335793457935579365793757938579395794057941579425794357944579455794657947579485794957950579515795257953579545795557956579575795857959579605796157962579635796457965579665796757968579695797057971579725797357974579755797657977579785797957980579815798257983579845798557986579875798857989579905799157992579935799457995579965799757998579995800058001580025800358004580055800658007580085800958010580115801258013580145801558016580175801858019580205802158022580235802458025580265802758028580295803058031580325803358034580355803658037580385803958040580415804258043580445804558046580475804858049580505805158052580535805458055580565805758058580595806058061580625806358064580655806658067580685806958070580715807258073580745807558076580775807858079580805808158082580835808458085580865808758088580895809058091580925809358094580955809658097580985809958100581015810258103581045810558106581075810858109581105811158112581135811458115581165811758118581195812058121581225812358124581255812658127581285812958130581315813258133581345813558136581375813858139581405814158142581435814458145581465814758148581495815058151581525815358154581555815658157581585815958160581615816258163581645816558166581675816858169581705817158172581735817458175581765817758178581795818058181581825818358184581855818658187581885818958190581915819258193581945819558196581975819858199582005820158202582035820458205582065820758208582095821058211582125821358214582155821658217582185821958220582215822258223582245822558226582275822858229582305823158232582335823458235582365823758238582395824058241582425824358244582455824658247582485824958250582515825258253582545825558256582575825858259582605826158262582635826458265582665826758268582695827058271582725827358274582755827658277582785827958280582815828258283582845828558286582875828858289582905829158292582935829458295582965829758298582995830058301583025830358304583055830658307583085830958310583115831258313583145831558316583175831858319583205832158322583235832458325583265832758328583295833058331583325833358334583355833658337583385833958340583415834258343583445834558346583475834858349583505835158352583535835458355583565835758358583595836058361583625836358364583655836658367583685836958370583715837258373583745837558376583775837858379583805838158382583835838458385583865838758388583895839058391583925839358394583955839658397583985839958400584015840258403584045840558406584075840858409584105841158412584135841458415584165841758418584195842058421584225842358424584255842658427584285842958430584315843258433584345843558436584375843858439584405844158442584435844458445584465844758448584495845058451584525845358454584555845658457584585845958460584615846258463584645846558466584675846858469584705847158472584735847458475584765847758478584795848058481584825848358484584855848658487584885848958490584915849258493584945849558496584975849858499585005850158502585035850458505585065850758508585095851058511585125851358514585155851658517585185851958520585215852258523585245852558526585275852858529585305853158532585335853458535585365853758538585395854058541585425854358544585455854658547585485854958550585515855258553585545855558556585575855858559585605856158562585635856458565585665856758568585695857058571585725857358574585755857658577585785857958580585815858258583585845858558586585875858858589585905859158592585935859458595585965859758598585995860058601586025860358604586055860658607586085860958610586115861258613586145861558616586175861858619586205862158622586235862458625586265862758628586295863058631586325863358634586355863658637586385863958640586415864258643586445864558646586475864858649586505865158652586535865458655586565865758658586595866058661586625866358664586655866658667586685866958670586715867258673586745867558676586775867858679586805868158682586835868458685586865868758688586895869058691586925869358694586955869658697586985869958700587015870258703587045870558706587075870858709587105871158712587135871458715587165871758718587195872058721587225872358724587255872658727587285872958730587315873258733587345873558736587375873858739587405874158742587435874458745587465874758748587495875058751587525875358754587555875658757587585875958760587615876258763587645876558766587675876858769587705877158772587735877458775587765877758778587795878058781587825878358784587855878658787587885878958790587915879258793587945879558796587975879858799588005880158802588035880458805588065880758808588095881058811588125881358814588155881658817588185881958820588215882258823588245882558826588275882858829588305883158832588335883458835588365883758838588395884058841588425884358844588455884658847588485884958850588515885258853588545885558856588575885858859588605886158862588635886458865588665886758868588695887058871588725887358874588755887658877588785887958880588815888258883588845888558886588875888858889588905889158892588935889458895588965889758898588995890058901589025890358904589055890658907589085890958910589115891258913589145891558916589175891858919589205892158922589235892458925589265892758928589295893058931589325893358934589355893658937589385893958940589415894258943589445894558946589475894858949589505895158952589535895458955589565895758958589595896058961589625896358964589655896658967589685896958970589715897258973589745897558976589775897858979589805898158982589835898458985589865898758988589895899058991589925899358994589955899658997589985899959000590015900259003590045900559006590075900859009590105901159012590135901459015590165901759018590195902059021590225902359024590255902659027590285902959030590315903259033590345903559036590375903859039590405904159042590435904459045590465904759048590495905059051590525905359054590555905659057590585905959060590615906259063590645906559066590675906859069590705907159072590735907459075590765907759078590795908059081590825908359084590855908659087590885908959090590915909259093590945909559096590975909859099591005910159102591035910459105591065910759108591095911059111591125911359114591155911659117591185911959120591215912259123591245912559126591275912859129591305913159132591335913459135591365913759138591395914059141591425914359144591455914659147591485914959150591515915259153591545915559156591575915859159591605916159162591635916459165591665916759168591695917059171591725917359174591755917659177591785917959180591815918259183591845918559186591875918859189591905919159192591935919459195591965919759198591995920059201592025920359204592055920659207592085920959210592115921259213592145921559216592175921859219592205922159222592235922459225592265922759228592295923059231592325923359234592355923659237592385923959240592415924259243592445924559246592475924859249592505925159252592535925459255592565925759258592595926059261592625926359264592655926659267592685926959270592715927259273592745927559276592775927859279592805928159282592835928459285592865928759288592895929059291592925929359294592955929659297592985929959300593015930259303593045930559306593075930859309593105931159312593135931459315593165931759318593195932059321593225932359324593255932659327593285932959330593315933259333593345933559336593375933859339593405934159342593435934459345593465934759348593495935059351593525935359354593555935659357593585935959360593615936259363593645936559366593675936859369593705937159372593735937459375593765937759378593795938059381593825938359384593855938659387593885938959390593915939259393593945939559396593975939859399594005940159402594035940459405594065940759408594095941059411594125941359414594155941659417594185941959420594215942259423594245942559426594275942859429594305943159432594335943459435594365943759438594395944059441594425944359444594455944659447594485944959450594515945259453594545945559456594575945859459594605946159462594635946459465594665946759468594695947059471594725947359474594755947659477594785947959480594815948259483594845948559486594875948859489594905949159492594935949459495594965949759498594995950059501595025950359504595055950659507595085950959510595115951259513595145951559516595175951859519595205952159522595235952459525595265952759528595295953059531595325953359534595355953659537595385953959540595415954259543595445954559546595475954859549595505955159552595535955459555595565955759558595595956059561595625956359564595655956659567595685956959570595715957259573595745957559576595775957859579595805958159582595835958459585595865958759588595895959059591595925959359594595955959659597595985959959600596015960259603596045960559606596075960859609596105961159612596135961459615596165961759618596195962059621596225962359624596255962659627596285962959630596315963259633596345963559636596375963859639596405964159642596435964459645596465964759648596495965059651596525965359654596555965659657596585965959660596615966259663596645966559666596675966859669596705967159672596735967459675596765967759678596795968059681596825968359684596855968659687596885968959690596915969259693596945969559696596975969859699597005970159702597035970459705597065970759708597095971059711597125971359714597155971659717597185971959720597215972259723597245972559726597275972859729597305973159732597335973459735597365973759738597395974059741597425974359744597455974659747597485974959750597515975259753597545975559756597575975859759597605976159762597635976459765597665976759768597695977059771597725977359774597755977659777597785977959780597815978259783597845978559786597875978859789597905979159792597935979459795597965979759798597995980059801598025980359804598055980659807598085980959810598115981259813598145981559816598175981859819598205982159822598235982459825598265982759828598295983059831598325983359834598355983659837598385983959840598415984259843598445984559846598475984859849598505985159852598535985459855598565985759858598595986059861598625986359864598655986659867598685986959870598715987259873598745987559876598775987859879598805988159882598835988459885598865988759888598895989059891598925989359894598955989659897598985989959900599015990259903599045990559906599075990859909599105991159912599135991459915599165991759918599195992059921599225992359924599255992659927599285992959930599315993259933599345993559936599375993859939599405994159942599435994459945599465994759948599495995059951599525995359954599555995659957599585995959960599615996259963599645996559966599675996859969599705997159972599735997459975599765997759978599795998059981599825998359984599855998659987599885998959990599915999259993599945999559996599975999859999600006000160002600036000460005600066000760008600096001060011600126001360014600156001660017600186001960020600216002260023600246002560026600276002860029600306003160032600336003460035600366003760038600396004060041600426004360044600456004660047600486004960050600516005260053600546005560056600576005860059600606006160062600636006460065600666006760068600696007060071600726007360074600756007660077600786007960080600816008260083600846008560086600876008860089600906009160092600936009460095600966009760098600996010060101601026010360104601056010660107601086010960110601116011260113601146011560116601176011860119601206012160122601236012460125601266012760128601296013060131601326013360134601356013660137601386013960140601416014260143601446014560146601476014860149601506015160152601536015460155601566015760158601596016060161601626016360164601656016660167601686016960170601716017260173601746017560176601776017860179601806018160182601836018460185601866018760188601896019060191601926019360194601956019660197601986019960200602016020260203602046020560206602076020860209602106021160212602136021460215602166021760218602196022060221602226022360224602256022660227602286022960230602316023260233602346023560236602376023860239602406024160242602436024460245602466024760248602496025060251602526025360254602556025660257602586025960260602616026260263602646026560266602676026860269602706027160272602736027460275602766027760278602796028060281602826028360284602856028660287602886028960290602916029260293602946029560296602976029860299603006030160302603036030460305603066030760308603096031060311603126031360314603156031660317603186031960320603216032260323603246032560326603276032860329603306033160332603336033460335603366033760338603396034060341603426034360344603456034660347603486034960350603516035260353603546035560356603576035860359603606036160362603636036460365603666036760368603696037060371603726037360374603756037660377603786037960380603816038260383603846038560386603876038860389603906039160392603936039460395603966039760398603996040060401604026040360404604056040660407604086040960410604116041260413604146041560416604176041860419604206042160422604236042460425604266042760428604296043060431604326043360434604356043660437604386043960440604416044260443604446044560446604476044860449604506045160452604536045460455604566045760458604596046060461604626046360464604656046660467604686046960470604716047260473604746047560476604776047860479604806048160482604836048460485604866048760488604896049060491604926049360494604956049660497604986049960500605016050260503605046050560506605076050860509605106051160512605136051460515605166051760518605196052060521605226052360524605256052660527605286052960530605316053260533605346053560536605376053860539605406054160542605436054460545605466054760548605496055060551605526055360554605556055660557605586055960560605616056260563605646056560566605676056860569605706057160572605736057460575605766057760578605796058060581605826058360584605856058660587605886058960590605916059260593605946059560596605976059860599606006060160602606036060460605606066060760608606096061060611606126061360614606156061660617606186061960620606216062260623606246062560626606276062860629606306063160632606336063460635606366063760638606396064060641606426064360644606456064660647606486064960650606516065260653606546065560656606576065860659606606066160662606636066460665606666066760668606696067060671606726067360674606756067660677606786067960680606816068260683606846068560686606876068860689606906069160692606936069460695606966069760698606996070060701607026070360704607056070660707607086070960710607116071260713607146071560716607176071860719607206072160722607236072460725607266072760728607296073060731607326073360734607356073660737607386073960740607416074260743607446074560746607476074860749607506075160752607536075460755607566075760758607596076060761607626076360764607656076660767607686076960770607716077260773607746077560776607776077860779607806078160782607836078460785607866078760788607896079060791607926079360794607956079660797607986079960800608016080260803608046080560806608076080860809608106081160812608136081460815608166081760818608196082060821608226082360824608256082660827608286082960830608316083260833608346083560836608376083860839608406084160842608436084460845608466084760848608496085060851608526085360854608556085660857608586085960860608616086260863608646086560866608676086860869608706087160872608736087460875608766087760878608796088060881608826088360884608856088660887608886088960890608916089260893608946089560896608976089860899609006090160902609036090460905609066090760908609096091060911609126091360914609156091660917609186091960920609216092260923609246092560926609276092860929609306093160932609336093460935609366093760938609396094060941609426094360944609456094660947609486094960950609516095260953609546095560956609576095860959609606096160962609636096460965609666096760968609696097060971609726097360974609756097660977609786097960980609816098260983609846098560986609876098860989609906099160992609936099460995609966099760998609996100061001610026100361004610056100661007610086100961010610116101261013610146101561016610176101861019610206102161022610236102461025610266102761028610296103061031610326103361034610356103661037610386103961040610416104261043610446104561046610476104861049610506105161052610536105461055610566105761058610596106061061610626106361064610656106661067610686106961070610716107261073610746107561076610776107861079610806108161082610836108461085610866108761088610896109061091610926109361094610956109661097610986109961100611016110261103611046110561106611076110861109611106111161112611136111461115611166111761118611196112061121611226112361124611256112661127611286112961130611316113261133611346113561136611376113861139611406114161142611436114461145611466114761148611496115061151611526115361154611556115661157611586115961160611616116261163611646116561166611676116861169611706117161172611736117461175611766117761178611796118061181611826118361184611856118661187611886118961190611916119261193611946119561196611976119861199612006120161202612036120461205612066120761208612096121061211612126121361214612156121661217612186121961220612216122261223612246122561226612276122861229612306123161232612336123461235612366123761238612396124061241612426124361244612456124661247612486124961250612516125261253612546125561256612576125861259612606126161262612636126461265612666126761268612696127061271612726127361274612756127661277612786127961280612816128261283612846128561286612876128861289612906129161292612936129461295612966129761298612996130061301613026130361304613056130661307613086130961310613116131261313613146131561316613176131861319613206132161322613236132461325613266132761328613296133061331613326133361334613356133661337613386133961340613416134261343613446134561346613476134861349613506135161352613536135461355613566135761358613596136061361613626136361364613656136661367613686136961370613716137261373613746137561376613776137861379613806138161382613836138461385613866138761388613896139061391613926139361394613956139661397613986139961400614016140261403614046140561406614076140861409614106141161412614136141461415614166141761418614196142061421614226142361424614256142661427614286142961430614316143261433614346143561436614376143861439614406144161442614436144461445614466144761448614496145061451614526145361454614556145661457614586145961460614616146261463614646146561466614676146861469614706147161472614736147461475614766147761478614796148061481614826148361484614856148661487614886148961490614916149261493614946149561496614976149861499615006150161502615036150461505615066150761508615096151061511615126151361514615156151661517615186151961520615216152261523615246152561526615276152861529615306153161532615336153461535615366153761538615396154061541615426154361544615456154661547615486154961550615516155261553615546155561556615576155861559615606156161562615636156461565615666156761568615696157061571615726157361574615756157661577615786157961580615816158261583615846158561586615876158861589615906159161592615936159461595615966159761598615996160061601616026160361604616056160661607616086160961610616116161261613616146161561616616176161861619616206162161622616236162461625616266162761628616296163061631616326163361634616356163661637616386163961640616416164261643616446164561646616476164861649616506165161652616536165461655616566165761658616596166061661616626166361664616656166661667616686166961670616716167261673616746167561676616776167861679616806168161682616836168461685616866168761688616896169061691616926169361694616956169661697616986169961700617016170261703617046170561706617076170861709617106171161712617136171461715617166171761718617196172061721617226172361724617256172661727617286172961730617316173261733617346173561736617376173861739617406174161742617436174461745617466174761748617496175061751617526175361754617556175661757617586175961760617616176261763617646176561766617676176861769617706177161772617736177461775617766177761778617796178061781617826178361784617856178661787617886178961790617916179261793617946179561796617976179861799618006180161802618036180461805618066180761808618096181061811618126181361814618156181661817618186181961820618216182261823618246182561826618276182861829618306183161832618336183461835618366183761838618396184061841618426184361844618456184661847618486184961850618516185261853618546185561856618576185861859618606186161862618636186461865618666186761868618696187061871618726187361874618756187661877618786187961880618816188261883618846188561886618876188861889618906189161892618936189461895618966189761898618996190061901619026190361904619056190661907619086190961910619116191261913619146191561916619176191861919619206192161922619236192461925619266192761928619296193061931619326193361934619356193661937619386193961940619416194261943619446194561946619476194861949619506195161952619536195461955619566195761958619596196061961619626196361964619656196661967619686196961970619716197261973619746197561976619776197861979619806198161982619836198461985619866198761988619896199061991619926199361994619956199661997619986199962000620016200262003620046200562006620076200862009620106201162012620136201462015620166201762018620196202062021620226202362024620256202662027620286202962030620316203262033620346203562036620376203862039620406204162042620436204462045620466204762048620496205062051620526205362054620556205662057620586205962060620616206262063620646206562066620676206862069620706207162072620736207462075620766207762078620796208062081620826208362084620856208662087620886208962090620916209262093620946209562096620976209862099621006210162102621036210462105621066210762108621096211062111621126211362114621156211662117621186211962120621216212262123621246212562126621276212862129621306213162132621336213462135621366213762138621396214062141621426214362144621456214662147621486214962150621516215262153621546215562156621576215862159621606216162162621636216462165621666216762168621696217062171621726217362174621756217662177621786217962180621816218262183621846218562186621876218862189621906219162192621936219462195621966219762198621996220062201622026220362204622056220662207622086220962210622116221262213622146221562216622176221862219622206222162222622236222462225622266222762228622296223062231622326223362234622356223662237622386223962240622416224262243622446224562246622476224862249622506225162252622536225462255622566225762258622596226062261622626226362264622656226662267622686226962270622716227262273622746227562276622776227862279622806228162282622836228462285622866228762288622896229062291622926229362294622956229662297622986229962300623016230262303623046230562306623076230862309623106231162312623136231462315623166231762318623196232062321623226232362324623256232662327623286232962330623316233262333623346233562336623376233862339623406234162342623436234462345623466234762348623496235062351623526235362354623556235662357623586235962360623616236262363623646236562366623676236862369623706237162372623736237462375623766237762378623796238062381623826238362384623856238662387623886238962390623916239262393623946239562396623976239862399624006240162402624036240462405624066240762408624096241062411624126241362414624156241662417624186241962420624216242262423624246242562426624276242862429624306243162432624336243462435624366243762438624396244062441624426244362444624456244662447624486244962450624516245262453624546245562456624576245862459624606246162462624636246462465624666246762468624696247062471624726247362474624756247662477624786247962480624816248262483624846248562486624876248862489624906249162492624936249462495624966249762498624996250062501625026250362504625056250662507625086250962510625116251262513625146251562516625176251862519625206252162522625236252462525625266252762528625296253062531625326253362534625356253662537625386253962540625416254262543625446254562546625476254862549625506255162552625536255462555625566255762558625596256062561625626256362564625656256662567625686256962570625716257262573625746257562576625776257862579625806258162582625836258462585625866258762588625896259062591625926259362594625956259662597625986259962600626016260262603626046260562606626076260862609626106261162612626136261462615626166261762618626196262062621626226262362624626256262662627626286262962630626316263262633626346263562636626376263862639626406264162642626436264462645626466264762648626496265062651626526265362654626556265662657626586265962660626616266262663626646266562666626676266862669626706267162672626736267462675626766267762678626796268062681626826268362684626856268662687626886268962690626916269262693626946269562696626976269862699627006270162702627036270462705627066270762708627096271062711627126271362714627156271662717627186271962720627216272262723627246272562726627276272862729627306273162732627336273462735627366273762738627396274062741627426274362744627456274662747627486274962750627516275262753627546275562756627576275862759627606276162762627636276462765627666276762768627696277062771627726277362774627756277662777627786277962780627816278262783627846278562786627876278862789627906279162792627936279462795627966279762798627996280062801628026280362804628056280662807628086280962810628116281262813628146281562816628176281862819628206282162822628236282462825628266282762828628296283062831628326283362834628356283662837628386283962840628416284262843628446284562846628476284862849628506285162852628536285462855628566285762858628596286062861628626286362864628656286662867628686286962870628716287262873628746287562876628776287862879628806288162882628836288462885628866288762888628896289062891628926289362894628956289662897628986289962900629016290262903629046290562906629076290862909629106291162912629136291462915629166291762918629196292062921629226292362924629256292662927629286292962930629316293262933629346293562936629376293862939629406294162942629436294462945629466294762948629496295062951629526295362954629556295662957629586295962960629616296262963629646296562966629676296862969629706297162972629736297462975629766297762978629796298062981629826298362984629856298662987629886298962990629916299262993629946299562996629976299862999630006300163002630036300463005630066300763008630096301063011630126301363014630156301663017630186301963020630216302263023630246302563026630276302863029630306303163032630336303463035630366303763038630396304063041630426304363044630456304663047630486304963050630516305263053630546305563056630576305863059630606306163062630636306463065630666306763068630696307063071630726307363074630756307663077630786307963080630816308263083630846308563086630876308863089630906309163092630936309463095630966309763098630996310063101631026310363104631056310663107631086310963110631116311263113631146311563116631176311863119631206312163122631236312463125631266312763128631296313063131631326313363134631356313663137631386313963140631416314263143631446314563146631476314863149631506315163152631536315463155631566315763158631596316063161631626316363164631656316663167631686316963170631716317263173631746317563176631776317863179631806318163182631836318463185631866318763188631896319063191631926319363194631956319663197631986319963200632016320263203632046320563206632076320863209632106321163212632136321463215632166321763218632196322063221632226322363224632256322663227632286322963230632316323263233632346323563236632376323863239632406324163242632436324463245632466324763248632496325063251632526325363254632556325663257632586325963260632616326263263632646326563266632676326863269632706327163272632736327463275632766327763278632796328063281632826328363284632856328663287632886328963290632916329263293632946329563296632976329863299633006330163302633036330463305633066330763308633096331063311633126331363314633156331663317633186331963320633216332263323633246332563326633276332863329633306333163332633336333463335633366333763338633396334063341633426334363344633456334663347633486334963350633516335263353633546335563356633576335863359633606336163362633636336463365633666336763368633696337063371633726337363374633756337663377633786337963380633816338263383633846338563386633876338863389633906339163392633936339463395633966339763398633996340063401634026340363404634056340663407634086340963410634116341263413634146341563416634176341863419634206342163422634236342463425634266342763428634296343063431634326343363434634356343663437634386343963440634416344263443634446344563446634476344863449634506345163452634536345463455634566345763458634596346063461634626346363464634656346663467634686346963470634716347263473634746347563476634776347863479634806348163482634836348463485634866348763488634896349063491634926349363494634956349663497634986349963500635016350263503635046350563506635076350863509635106351163512635136351463515635166351763518635196352063521635226352363524635256352663527635286352963530635316353263533635346353563536635376353863539635406354163542635436354463545635466354763548635496355063551635526355363554635556355663557635586355963560635616356263563635646356563566635676356863569635706357163572635736357463575635766357763578635796358063581635826358363584635856358663587635886358963590635916359263593635946359563596635976359863599636006360163602636036360463605636066360763608636096361063611636126361363614636156361663617636186361963620636216362263623636246362563626636276362863629636306363163632636336363463635636366363763638636396364063641636426364363644636456364663647636486364963650636516365263653636546365563656636576365863659636606366163662636636366463665636666366763668636696367063671636726367363674636756367663677636786367963680636816368263683636846368563686636876368863689636906369163692636936369463695636966369763698636996370063701637026370363704637056370663707637086370963710637116371263713637146371563716637176371863719637206372163722637236372463725637266372763728637296373063731637326373363734637356373663737637386373963740637416374263743637446374563746637476374863749637506375163752637536375463755637566375763758637596376063761637626376363764637656376663767637686376963770637716377263773637746377563776637776377863779637806378163782637836378463785637866378763788637896379063791637926379363794637956379663797637986379963800638016380263803638046380563806638076380863809638106381163812638136381463815638166381763818638196382063821638226382363824638256382663827638286382963830638316383263833638346383563836638376383863839638406384163842638436384463845638466384763848638496385063851638526385363854638556385663857638586385963860638616386263863638646386563866638676386863869638706387163872638736387463875638766387763878638796388063881638826388363884638856388663887638886388963890638916389263893638946389563896638976389863899639006390163902639036390463905639066390763908639096391063911639126391363914639156391663917639186391963920639216392263923639246392563926639276392863929639306393163932639336393463935639366393763938639396394063941639426394363944639456394663947639486394963950639516395263953639546395563956639576395863959639606396163962639636396463965639666396763968639696397063971639726397363974639756397663977639786397963980639816398263983639846398563986639876398863989639906399163992639936399463995639966399763998639996400064001640026400364004640056400664007640086400964010640116401264013640146401564016640176401864019640206402164022640236402464025640266402764028640296403064031640326403364034640356403664037640386403964040640416404264043640446404564046640476404864049640506405164052640536405464055640566405764058640596406064061640626406364064640656406664067640686406964070640716407264073640746407564076640776407864079640806408164082640836408464085640866408764088640896409064091640926409364094640956409664097640986409964100641016410264103641046410564106641076410864109641106411164112641136411464115641166411764118641196412064121641226412364124641256412664127641286412964130641316413264133641346413564136641376413864139641406414164142641436414464145641466414764148641496415064151641526415364154641556415664157641586415964160641616416264163641646416564166641676416864169641706417164172641736417464175641766417764178641796418064181641826418364184641856418664187641886418964190641916419264193641946419564196641976419864199642006420164202642036420464205642066420764208642096421064211642126421364214642156421664217642186421964220642216422264223642246422564226642276422864229642306423164232642336423464235642366423764238642396424064241642426424364244642456424664247642486424964250642516425264253642546425564256642576425864259642606426164262642636426464265642666426764268642696427064271642726427364274642756427664277642786427964280642816428264283642846428564286642876428864289642906429164292642936429464295642966429764298642996430064301643026430364304643056430664307643086430964310643116431264313643146431564316643176431864319643206432164322643236432464325643266432764328643296433064331643326433364334643356433664337643386433964340643416434264343643446434564346643476434864349643506435164352643536435464355643566435764358643596436064361643626436364364643656436664367643686436964370643716437264373643746437564376643776437864379643806438164382643836438464385643866438764388643896439064391643926439364394643956439664397643986439964400644016440264403644046440564406644076440864409644106441164412644136441464415644166441764418644196442064421644226442364424644256442664427644286442964430644316443264433644346443564436644376443864439644406444164442644436444464445644466444764448644496445064451644526445364454644556445664457644586445964460644616446264463644646446564466644676446864469644706447164472644736447464475644766447764478644796448064481644826448364484644856448664487644886448964490644916449264493644946449564496644976449864499645006450164502645036450464505645066450764508645096451064511645126451364514645156451664517645186451964520645216452264523645246452564526645276452864529645306453164532645336453464535645366453764538645396454064541645426454364544645456454664547645486454964550645516455264553645546455564556645576455864559645606456164562645636456464565645666456764568645696457064571645726457364574645756457664577645786457964580645816458264583645846458564586645876458864589645906459164592645936459464595645966459764598645996460064601646026460364604646056460664607646086460964610646116461264613646146461564616646176461864619646206462164622646236462464625646266462764628646296463064631646326463364634646356463664637646386463964640646416464264643646446464564646646476464864649646506465164652646536465464655646566465764658646596466064661646626466364664646656466664667646686466964670646716467264673646746467564676646776467864679646806468164682646836468464685646866468764688646896469064691646926469364694646956469664697646986469964700647016470264703647046470564706647076470864709647106471164712647136471464715647166471764718647196472064721647226472364724647256472664727647286472964730647316473264733647346473564736647376473864739647406474164742647436474464745647466474764748647496475064751647526475364754647556475664757647586475964760647616476264763647646476564766647676476864769647706477164772647736477464775647766477764778647796478064781647826478364784647856478664787647886478964790647916479264793647946479564796647976479864799648006480164802648036480464805648066480764808648096481064811648126481364814648156481664817648186481964820648216482264823648246482564826648276482864829648306483164832648336483464835648366483764838648396484064841648426484364844648456484664847648486484964850648516485264853648546485564856648576485864859648606486164862648636486464865648666486764868648696487064871648726487364874648756487664877648786487964880648816488264883648846488564886648876488864889648906489164892648936489464895648966489764898648996490064901649026490364904649056490664907649086490964910649116491264913649146491564916649176491864919649206492164922649236492464925649266492764928649296493064931649326493364934649356493664937649386493964940649416494264943649446494564946649476494864949649506495164952649536495464955649566495764958649596496064961649626496364964649656496664967649686496964970649716497264973649746497564976649776497864979649806498164982649836498464985649866498764988649896499064991649926499364994649956499664997649986499965000650016500265003650046500565006650076500865009650106501165012650136501465015650166501765018650196502065021650226502365024650256502665027650286502965030650316503265033650346503565036650376503865039650406504165042650436504465045650466504765048650496505065051650526505365054650556505665057650586505965060650616506265063650646506565066650676506865069650706507165072650736507465075650766507765078650796508065081650826508365084650856508665087650886508965090650916509265093650946509565096650976509865099651006510165102651036510465105651066510765108651096511065111651126511365114651156511665117651186511965120651216512265123651246512565126651276512865129651306513165132651336513465135651366513765138651396514065141651426514365144651456514665147651486514965150651516515265153651546515565156651576515865159651606516165162651636516465165651666516765168651696517065171651726517365174651756517665177651786517965180651816518265183651846518565186651876518865189651906519165192651936519465195651966519765198651996520065201652026520365204652056520665207652086520965210652116521265213652146521565216652176521865219652206522165222652236522465225652266522765228652296523065231652326523365234652356523665237652386523965240652416524265243652446524565246652476524865249652506525165252652536525465255652566525765258652596526065261652626526365264652656526665267652686526965270652716527265273652746527565276652776527865279652806528165282652836528465285652866528765288652896529065291652926529365294652956529665297652986529965300653016530265303653046530565306653076530865309653106531165312653136531465315653166531765318653196532065321653226532365324653256532665327653286532965330653316533265333653346533565336653376533865339653406534165342653436534465345653466534765348653496535065351653526535365354653556535665357653586535965360653616536265363653646536565366653676536865369653706537165372653736537465375653766537765378653796538065381653826538365384653856538665387653886538965390653916539265393653946539565396653976539865399654006540165402654036540465405654066540765408654096541065411654126541365414654156541665417654186541965420654216542265423654246542565426654276542865429654306543165432654336543465435654366543765438654396544065441654426544365444654456544665447654486544965450654516545265453654546545565456654576545865459654606546165462654636546465465654666546765468654696547065471654726547365474654756547665477654786547965480654816548265483654846548565486654876548865489654906549165492654936549465495654966549765498654996550065501655026550365504655056550665507655086550965510655116551265513655146551565516655176551865519655206552165522655236552465525655266552765528655296553065531655326553365534655356553665537655386553965540655416554265543655446554565546655476554865549655506555165552655536555465555655566555765558655596556065561655626556365564655656556665567655686556965570655716557265573655746557565576655776557865579655806558165582655836558465585655866558765588655896559065591655926559365594655956559665597655986559965600656016560265603656046560565606656076560865609656106561165612656136561465615656166561765618656196562065621656226562365624656256562665627656286562965630656316563265633656346563565636656376563865639656406564165642656436564465645656466564765648656496565065651656526565365654656556565665657656586565965660656616566265663656646566565666656676566865669656706567165672656736567465675656766567765678656796568065681656826568365684656856568665687656886568965690656916569265693656946569565696656976569865699657006570165702657036570465705657066570765708657096571065711657126571365714657156571665717657186571965720657216572265723657246572565726657276572865729657306573165732657336573465735657366573765738657396574065741657426574365744657456574665747657486574965750657516575265753657546575565756657576575865759657606576165762657636576465765657666576765768657696577065771657726577365774657756577665777657786577965780657816578265783657846578565786657876578865789657906579165792657936579465795657966579765798657996580065801658026580365804658056580665807658086580965810658116581265813658146581565816658176581865819658206582165822658236582465825658266582765828658296583065831658326583365834658356583665837658386583965840658416584265843658446584565846658476584865849658506585165852658536585465855658566585765858658596586065861658626586365864658656586665867658686586965870658716587265873658746587565876658776587865879658806588165882658836588465885658866588765888658896589065891658926589365894658956589665897658986589965900659016590265903659046590565906659076590865909659106591165912659136591465915659166591765918659196592065921659226592365924659256592665927659286592965930659316593265933659346593565936659376593865939659406594165942659436594465945659466594765948659496595065951659526595365954659556595665957659586595965960659616596265963659646596565966659676596865969659706597165972659736597465975659766597765978659796598065981659826598365984659856598665987659886598965990659916599265993659946599565996659976599865999660006600166002660036600466005660066600766008660096601066011660126601366014660156601666017660186601966020660216602266023660246602566026660276602866029660306603166032660336603466035660366603766038660396604066041660426604366044660456604666047660486604966050660516605266053660546605566056660576605866059660606606166062660636606466065660666606766068660696607066071660726607366074660756607666077660786607966080660816608266083660846608566086660876608866089660906609166092660936609466095660966609766098660996610066101661026610366104661056610666107661086610966110661116611266113661146611566116661176611866119661206612166122661236612466125661266612766128661296613066131661326613366134661356613666137661386613966140661416614266143661446614566146661476614866149661506615166152661536615466155661566615766158661596616066161661626616366164661656616666167661686616966170661716617266173661746617566176661776617866179661806618166182661836618466185661866618766188661896619066191661926619366194661956619666197661986619966200662016620266203662046620566206662076620866209662106621166212662136621466215662166621766218662196622066221662226622366224662256622666227662286622966230662316623266233662346623566236662376623866239662406624166242662436624466245662466624766248662496625066251662526625366254662556625666257662586625966260662616626266263662646626566266662676626866269662706627166272662736627466275662766627766278662796628066281662826628366284662856628666287662886628966290662916629266293662946629566296662976629866299663006630166302663036630466305663066630766308663096631066311663126631366314663156631666317663186631966320663216632266323663246632566326663276632866329663306633166332663336633466335663366633766338663396634066341663426634366344663456634666347663486634966350663516635266353663546635566356663576635866359663606636166362663636636466365663666636766368663696637066371663726637366374663756637666377663786637966380663816638266383663846638566386663876638866389663906639166392663936639466395663966639766398663996640066401664026640366404664056640666407664086640966410664116641266413664146641566416664176641866419664206642166422664236642466425664266642766428664296643066431664326643366434664356643666437664386643966440664416644266443664446644566446664476644866449664506645166452664536645466455664566645766458664596646066461664626646366464664656646666467664686646966470664716647266473664746647566476664776647866479664806648166482664836648466485664866648766488664896649066491664926649366494664956649666497664986649966500665016650266503665046650566506665076650866509665106651166512665136651466515665166651766518665196652066521665226652366524665256652666527665286652966530665316653266533665346653566536665376653866539665406654166542665436654466545665466654766548665496655066551665526655366554665556655666557665586655966560665616656266563665646656566566665676656866569665706657166572665736657466575665766657766578665796658066581665826658366584665856658666587665886658966590665916659266593665946659566596665976659866599666006660166602666036660466605666066660766608666096661066611666126661366614666156661666617666186661966620666216662266623666246662566626666276662866629666306663166632666336663466635666366663766638666396664066641666426664366644666456664666647666486664966650666516665266653666546665566656666576665866659666606666166662666636666466665666666666766668666696667066671666726667366674666756667666677666786667966680666816668266683666846668566686666876668866689666906669166692666936669466695666966669766698666996670066701667026670366704667056670666707667086670966710667116671266713667146671566716667176671866719667206672166722667236672466725667266672766728667296673066731667326673366734667356673666737667386673966740667416674266743667446674566746667476674866749667506675166752667536675466755667566675766758667596676066761667626676366764667656676666767667686676966770667716677266773667746677566776667776677866779667806678166782667836678466785667866678766788667896679066791667926679366794667956679666797667986679966800668016680266803668046680566806668076680866809668106681166812668136681466815668166681766818668196682066821668226682366824668256682666827668286682966830668316683266833668346683566836668376683866839668406684166842668436684466845668466684766848668496685066851668526685366854668556685666857668586685966860668616686266863668646686566866668676686866869668706687166872668736687466875668766687766878668796688066881668826688366884668856688666887668886688966890668916689266893668946689566896668976689866899669006690166902669036690466905669066690766908669096691066911669126691366914669156691666917669186691966920669216692266923669246692566926669276692866929669306693166932669336693466935669366693766938669396694066941669426694366944669456694666947669486694966950669516695266953669546695566956669576695866959669606696166962669636696466965669666696766968669696697066971669726697366974669756697666977669786697966980669816698266983669846698566986669876698866989669906699166992669936699466995669966699766998669996700067001670026700367004670056700667007670086700967010670116701267013670146701567016670176701867019670206702167022670236702467025670266702767028670296703067031670326703367034670356703667037670386703967040670416704267043670446704567046670476704867049670506705167052670536705467055670566705767058670596706067061670626706367064670656706667067670686706967070670716707267073670746707567076670776707867079670806708167082670836708467085670866708767088670896709067091670926709367094670956709667097670986709967100671016710267103671046710567106671076710867109671106711167112671136711467115671166711767118671196712067121671226712367124671256712667127671286712967130671316713267133671346713567136671376713867139671406714167142671436714467145671466714767148671496715067151671526715367154671556715667157671586715967160671616716267163671646716567166671676716867169671706717167172671736717467175671766717767178671796718067181671826718367184671856718667187671886718967190671916719267193671946719567196671976719867199672006720167202672036720467205672066720767208672096721067211672126721367214672156721667217672186721967220672216722267223672246722567226672276722867229672306723167232672336723467235672366723767238672396724067241672426724367244672456724667247672486724967250672516725267253672546725567256672576725867259672606726167262672636726467265672666726767268672696727067271672726727367274672756727667277672786727967280672816728267283672846728567286672876728867289672906729167292672936729467295672966729767298672996730067301673026730367304673056730667307673086730967310673116731267313673146731567316673176731867319673206732167322673236732467325673266732767328673296733067331673326733367334673356733667337673386733967340673416734267343673446734567346673476734867349673506735167352673536735467355673566735767358673596736067361673626736367364673656736667367673686736967370673716737267373673746737567376673776737867379673806738167382673836738467385673866738767388673896739067391673926739367394673956739667397673986739967400674016740267403674046740567406674076740867409674106741167412674136741467415674166741767418674196742067421674226742367424674256742667427674286742967430674316743267433674346743567436674376743867439674406744167442674436744467445674466744767448674496745067451674526745367454674556745667457674586745967460674616746267463674646746567466674676746867469674706747167472674736747467475674766747767478674796748067481674826748367484674856748667487674886748967490674916749267493674946749567496674976749867499675006750167502675036750467505675066750767508675096751067511675126751367514675156751667517675186751967520675216752267523675246752567526675276752867529675306753167532675336753467535675366753767538675396754067541675426754367544675456754667547675486754967550675516755267553675546755567556675576755867559675606756167562675636756467565675666756767568675696757067571675726757367574675756757667577675786757967580675816758267583675846758567586675876758867589675906759167592675936759467595675966759767598675996760067601676026760367604676056760667607676086760967610676116761267613676146761567616676176761867619676206762167622676236762467625676266762767628676296763067631676326763367634676356763667637676386763967640676416764267643676446764567646676476764867649676506765167652676536765467655676566765767658676596766067661676626766367664676656766667667676686766967670676716767267673676746767567676676776767867679676806768167682676836768467685676866768767688676896769067691676926769367694676956769667697676986769967700677016770267703677046770567706677076770867709677106771167712677136771467715677166771767718677196772067721677226772367724677256772667727677286772967730677316773267733677346773567736677376773867739677406774167742677436774467745677466774767748677496775067751677526775367754677556775667757677586775967760677616776267763677646776567766677676776867769677706777167772677736777467775677766777767778677796778067781677826778367784677856778667787677886778967790677916779267793677946779567796677976779867799678006780167802678036780467805678066780767808678096781067811678126781367814678156781667817678186781967820678216782267823678246782567826678276782867829678306783167832678336783467835678366783767838678396784067841678426784367844678456784667847678486784967850678516785267853678546785567856678576785867859678606786167862678636786467865678666786767868678696787067871678726787367874678756787667877678786787967880678816788267883678846788567886678876788867889678906789167892678936789467895678966789767898678996790067901679026790367904679056790667907679086790967910679116791267913679146791567916679176791867919679206792167922679236792467925679266792767928679296793067931679326793367934679356793667937679386793967940679416794267943679446794567946679476794867949679506795167952679536795467955679566795767958679596796067961679626796367964679656796667967679686796967970679716797267973679746797567976679776797867979679806798167982679836798467985679866798767988679896799067991679926799367994679956799667997679986799968000680016800268003680046800568006680076800868009680106801168012680136801468015680166801768018680196802068021680226802368024680256802668027680286802968030680316803268033680346803568036680376803868039680406804168042680436804468045680466804768048680496805068051680526805368054680556805668057680586805968060680616806268063680646806568066680676806868069680706807168072680736807468075680766807768078680796808068081680826808368084680856808668087680886808968090680916809268093680946809568096680976809868099681006810168102681036810468105681066810768108681096811068111681126811368114681156811668117681186811968120681216812268123681246812568126681276812868129681306813168132681336813468135681366813768138681396814068141681426814368144681456814668147681486814968150681516815268153681546815568156681576815868159681606816168162681636816468165681666816768168681696817068171681726817368174681756817668177681786817968180681816818268183681846818568186681876818868189681906819168192681936819468195681966819768198681996820068201682026820368204682056820668207682086820968210682116821268213682146821568216682176821868219682206822168222682236822468225682266822768228682296823068231682326823368234682356823668237682386823968240682416824268243682446824568246682476824868249682506825168252682536825468255682566825768258682596826068261682626826368264682656826668267682686826968270682716827268273682746827568276682776827868279682806828168282682836828468285682866828768288682896829068291682926829368294682956829668297682986829968300683016830268303683046830568306683076830868309683106831168312683136831468315683166831768318683196832068321683226832368324683256832668327683286832968330683316833268333683346833568336683376833868339683406834168342683436834468345683466834768348683496835068351683526835368354683556835668357683586835968360683616836268363683646836568366683676836868369683706837168372683736837468375683766837768378683796838068381683826838368384683856838668387683886838968390683916839268393683946839568396683976839868399684006840168402684036840468405684066840768408684096841068411684126841368414684156841668417684186841968420684216842268423684246842568426684276842868429684306843168432684336843468435684366843768438684396844068441684426844368444684456844668447684486844968450684516845268453684546845568456684576845868459684606846168462684636846468465684666846768468684696847068471684726847368474684756847668477684786847968480684816848268483684846848568486684876848868489684906849168492684936849468495684966849768498684996850068501685026850368504685056850668507685086850968510685116851268513685146851568516685176851868519685206852168522685236852468525685266852768528685296853068531685326853368534685356853668537685386853968540685416854268543685446854568546685476854868549685506855168552685536855468555685566855768558685596856068561685626856368564685656856668567685686856968570685716857268573685746857568576685776857868579685806858168582685836858468585685866858768588685896859068591685926859368594685956859668597685986859968600686016860268603686046860568606686076860868609686106861168612686136861468615686166861768618686196862068621686226862368624686256862668627686286862968630686316863268633686346863568636686376863868639686406864168642686436864468645686466864768648686496865068651686526865368654686556865668657686586865968660686616866268663686646866568666686676866868669686706867168672686736867468675686766867768678686796868068681686826868368684686856868668687686886868968690686916869268693686946869568696686976869868699687006870168702687036870468705687066870768708687096871068711687126871368714687156871668717687186871968720687216872268723687246872568726687276872868729687306873168732687336873468735687366873768738687396874068741687426874368744687456874668747687486874968750687516875268753687546875568756687576875868759687606876168762687636876468765687666876768768687696877068771687726877368774687756877668777687786877968780687816878268783687846878568786687876878868789687906879168792687936879468795687966879768798687996880068801688026880368804688056880668807688086880968810688116881268813688146881568816688176881868819688206882168822688236882468825688266882768828688296883068831688326883368834688356883668837688386883968840688416884268843688446884568846688476884868849688506885168852688536885468855688566885768858688596886068861688626886368864688656886668867688686886968870688716887268873688746887568876688776887868879688806888168882688836888468885688866888768888688896889068891688926889368894688956889668897688986889968900689016890268903689046890568906689076890868909689106891168912689136891468915689166891768918689196892068921689226892368924689256892668927689286892968930689316893268933689346893568936689376893868939689406894168942689436894468945689466894768948689496895068951689526895368954689556895668957689586895968960689616896268963689646896568966689676896868969689706897168972689736897468975689766897768978689796898068981689826898368984689856898668987689886898968990689916899268993689946899568996689976899868999690006900169002690036900469005690066900769008690096901069011690126901369014690156901669017690186901969020690216902269023690246902569026690276902869029690306903169032690336903469035690366903769038690396904069041690426904369044690456904669047690486904969050690516905269053690546905569056690576905869059690606906169062690636906469065690666906769068690696907069071690726907369074690756907669077690786907969080690816908269083690846908569086690876908869089690906909169092690936909469095690966909769098690996910069101691026910369104691056910669107691086910969110691116911269113691146911569116691176911869119691206912169122691236912469125691266912769128691296913069131691326913369134691356913669137691386913969140691416914269143691446914569146691476914869149691506915169152691536915469155691566915769158691596916069161691626916369164691656916669167691686916969170691716917269173691746917569176691776917869179691806918169182691836918469185691866918769188691896919069191691926919369194691956919669197691986919969200692016920269203692046920569206692076920869209692106921169212692136921469215692166921769218692196922069221692226922369224692256922669227692286922969230692316923269233692346923569236692376923869239692406924169242692436924469245692466924769248692496925069251692526925369254692556925669257692586925969260692616926269263692646926569266692676926869269692706927169272692736927469275692766927769278692796928069281692826928369284692856928669287692886928969290692916929269293692946929569296692976929869299693006930169302693036930469305693066930769308693096931069311693126931369314693156931669317693186931969320693216932269323693246932569326693276932869329693306933169332693336933469335693366933769338693396934069341693426934369344693456934669347693486934969350693516935269353693546935569356693576935869359693606936169362693636936469365693666936769368693696937069371693726937369374693756937669377693786937969380693816938269383693846938569386693876938869389693906939169392693936939469395693966939769398693996940069401694026940369404694056940669407694086940969410694116941269413694146941569416694176941869419694206942169422694236942469425694266942769428694296943069431694326943369434694356943669437694386943969440694416944269443694446944569446694476944869449694506945169452694536945469455694566945769458694596946069461694626946369464694656946669467694686946969470694716947269473694746947569476694776947869479694806948169482694836948469485694866948769488694896949069491694926949369494694956949669497694986949969500695016950269503695046950569506695076950869509695106951169512695136951469515695166951769518695196952069521695226952369524695256952669527695286952969530695316953269533695346953569536695376953869539695406954169542695436954469545695466954769548695496955069551695526955369554695556955669557695586955969560695616956269563695646956569566695676956869569695706957169572695736957469575695766957769578695796958069581695826958369584695856958669587695886958969590695916959269593695946959569596695976959869599696006960169602696036960469605696066960769608696096961069611696126961369614696156961669617696186961969620696216962269623696246962569626696276962869629696306963169632696336963469635696366963769638696396964069641696426964369644696456964669647696486964969650696516965269653696546965569656696576965869659696606966169662696636966469665696666966769668696696967069671696726967369674696756967669677696786967969680696816968269683696846968569686696876968869689696906969169692696936969469695696966969769698696996970069701697026970369704697056970669707697086970969710697116971269713697146971569716697176971869719697206972169722697236972469725697266972769728697296973069731697326973369734697356973669737697386973969740697416974269743697446974569746697476974869749697506975169752697536975469755697566975769758697596976069761697626976369764697656976669767697686976969770697716977269773697746977569776697776977869779697806978169782697836978469785697866978769788697896979069791697926979369794697956979669797697986979969800698016980269803698046980569806698076980869809698106981169812698136981469815698166981769818698196982069821698226982369824698256982669827698286982969830698316983269833698346983569836698376983869839698406984169842698436984469845698466984769848698496985069851698526985369854698556985669857698586985969860698616986269863698646986569866698676986869869698706987169872698736987469875698766987769878698796988069881698826988369884698856988669887698886988969890698916989269893698946989569896698976989869899699006990169902699036990469905699066990769908699096991069911699126991369914699156991669917699186991969920699216992269923699246992569926699276992869929699306993169932699336993469935699366993769938699396994069941699426994369944699456994669947699486994969950699516995269953699546995569956699576995869959699606996169962699636996469965699666996769968699696997069971699726997369974699756997669977699786997969980699816998269983699846998569986699876998869989699906999169992699936999469995699966999769998699997000070001700027000370004700057000670007700087000970010700117001270013700147001570016700177001870019700207002170022700237002470025700267002770028700297003070031700327003370034700357003670037700387003970040700417004270043700447004570046700477004870049700507005170052700537005470055700567005770058700597006070061700627006370064700657006670067700687006970070700717007270073700747007570076700777007870079700807008170082700837008470085700867008770088700897009070091700927009370094700957009670097700987009970100701017010270103701047010570106701077010870109701107011170112701137011470115701167011770118701197012070121701227012370124701257012670127701287012970130701317013270133701347013570136701377013870139701407014170142701437014470145701467014770148701497015070151701527015370154701557015670157701587015970160701617016270163701647016570166701677016870169701707017170172701737017470175701767017770178701797018070181701827018370184701857018670187701887018970190701917019270193701947019570196701977019870199702007020170202702037020470205702067020770208702097021070211702127021370214702157021670217702187021970220702217022270223702247022570226702277022870229702307023170232702337023470235702367023770238702397024070241702427024370244702457024670247702487024970250702517025270253702547025570256702577025870259702607026170262702637026470265702667026770268702697027070271702727027370274702757027670277702787027970280702817028270283702847028570286702877028870289702907029170292702937029470295702967029770298702997030070301703027030370304703057030670307703087030970310703117031270313703147031570316703177031870319703207032170322703237032470325703267032770328703297033070331703327033370334703357033670337703387033970340703417034270343703447034570346703477034870349703507035170352703537035470355703567035770358703597036070361703627036370364703657036670367703687036970370703717037270373703747037570376703777037870379703807038170382703837038470385703867038770388703897039070391703927039370394703957039670397703987039970400704017040270403704047040570406704077040870409704107041170412704137041470415704167041770418704197042070421704227042370424704257042670427704287042970430704317043270433704347043570436704377043870439704407044170442704437044470445704467044770448704497045070451704527045370454704557045670457704587045970460704617046270463704647046570466704677046870469704707047170472704737047470475704767047770478704797048070481704827048370484704857048670487704887048970490704917049270493704947049570496704977049870499705007050170502705037050470505705067050770508705097051070511705127051370514705157051670517705187051970520705217052270523705247052570526705277052870529705307053170532705337053470535705367053770538705397054070541705427054370544705457054670547705487054970550705517055270553705547055570556705577055870559705607056170562705637056470565705667056770568705697057070571705727057370574705757057670577705787057970580705817058270583705847058570586705877058870589705907059170592705937059470595705967059770598705997060070601706027060370604706057060670607706087060970610706117061270613706147061570616706177061870619706207062170622706237062470625706267062770628706297063070631706327063370634706357063670637706387063970640706417064270643706447064570646706477064870649706507065170652706537065470655706567065770658706597066070661706627066370664706657066670667706687066970670706717067270673706747067570676706777067870679706807068170682706837068470685706867068770688706897069070691706927069370694706957069670697706987069970700707017070270703707047070570706707077070870709707107071170712707137071470715707167071770718707197072070721707227072370724707257072670727707287072970730707317073270733707347073570736707377073870739707407074170742707437074470745707467074770748707497075070751707527075370754707557075670757707587075970760707617076270763707647076570766707677076870769707707077170772707737077470775707767077770778707797078070781707827078370784707857078670787707887078970790707917079270793707947079570796707977079870799708007080170802708037080470805708067080770808708097081070811708127081370814708157081670817708187081970820708217082270823708247082570826708277082870829708307083170832708337083470835708367083770838708397084070841708427084370844708457084670847708487084970850708517085270853708547085570856708577085870859708607086170862708637086470865708667086770868708697087070871708727087370874708757087670877708787087970880708817088270883708847088570886708877088870889708907089170892708937089470895708967089770898708997090070901709027090370904709057090670907709087090970910709117091270913709147091570916709177091870919709207092170922709237092470925709267092770928709297093070931709327093370934709357093670937709387093970940709417094270943709447094570946709477094870949709507095170952709537095470955709567095770958709597096070961709627096370964709657096670967709687096970970709717097270973709747097570976709777097870979709807098170982709837098470985709867098770988709897099070991709927099370994709957099670997709987099971000710017100271003710047100571006710077100871009710107101171012710137101471015710167101771018710197102071021710227102371024710257102671027710287102971030710317103271033710347103571036710377103871039710407104171042710437104471045710467104771048710497105071051710527105371054710557105671057710587105971060710617106271063710647106571066710677106871069710707107171072710737107471075710767107771078710797108071081710827108371084710857108671087710887108971090710917109271093710947109571096710977109871099711007110171102711037110471105711067110771108711097111071111711127111371114711157111671117711187111971120711217112271123711247112571126711277112871129711307113171132711337113471135711367113771138711397114071141711427114371144711457114671147711487114971150711517115271153711547115571156711577115871159711607116171162711637116471165711667116771168711697117071171711727117371174711757117671177711787117971180711817118271183711847118571186711877118871189711907119171192711937119471195711967119771198711997120071201712027120371204712057120671207712087120971210712117121271213712147121571216712177121871219712207122171222712237122471225712267122771228712297123071231712327123371234712357123671237712387123971240712417124271243712447124571246712477124871249712507125171252712537125471255712567125771258712597126071261712627126371264712657126671267712687126971270712717127271273712747127571276712777127871279712807128171282712837128471285712867128771288712897129071291712927129371294712957129671297712987129971300713017130271303713047130571306713077130871309713107131171312713137131471315713167131771318713197132071321713227132371324713257132671327713287132971330713317133271333713347133571336713377133871339713407134171342713437134471345713467134771348713497135071351713527135371354713557135671357713587135971360713617136271363713647136571366713677136871369713707137171372713737137471375713767137771378713797138071381713827138371384713857138671387713887138971390713917139271393713947139571396713977139871399714007140171402714037140471405714067140771408714097141071411714127141371414714157141671417714187141971420714217142271423714247142571426714277142871429714307143171432714337143471435714367143771438714397144071441714427144371444714457144671447714487144971450714517145271453714547145571456714577145871459714607146171462714637146471465714667146771468714697147071471714727147371474714757147671477714787147971480714817148271483714847148571486714877148871489714907149171492714937149471495714967149771498714997150071501715027150371504715057150671507715087150971510715117151271513715147151571516715177151871519715207152171522715237152471525715267152771528715297153071531715327153371534715357153671537715387153971540715417154271543715447154571546715477154871549715507155171552715537155471555715567155771558715597156071561715627156371564715657156671567715687156971570715717157271573715747157571576715777157871579715807158171582715837158471585715867158771588715897159071591715927159371594715957159671597715987159971600716017160271603716047160571606716077160871609716107161171612716137161471615716167161771618716197162071621716227162371624716257162671627716287162971630716317163271633716347163571636716377163871639716407164171642716437164471645716467164771648716497165071651716527165371654716557165671657716587165971660716617166271663716647166571666716677166871669716707167171672716737167471675716767167771678716797168071681716827168371684716857168671687716887168971690716917169271693716947169571696716977169871699717007170171702717037170471705717067170771708717097171071711717127171371714717157171671717717187171971720717217172271723717247172571726717277172871729717307173171732717337173471735717367173771738717397174071741717427174371744717457174671747717487174971750717517175271753717547175571756717577175871759717607176171762717637176471765717667176771768717697177071771717727177371774717757177671777717787177971780717817178271783717847178571786717877178871789717907179171792717937179471795717967179771798717997180071801718027180371804718057180671807718087180971810718117181271813718147181571816718177181871819718207182171822718237182471825718267182771828718297183071831718327183371834718357183671837718387183971840718417184271843718447184571846718477184871849718507185171852718537185471855718567185771858718597186071861718627186371864718657186671867718687186971870718717187271873718747187571876718777187871879718807188171882718837188471885718867188771888718897189071891718927189371894718957189671897718987189971900719017190271903719047190571906719077190871909719107191171912719137191471915719167191771918719197192071921719227192371924719257192671927719287192971930719317193271933719347193571936719377193871939719407194171942719437194471945719467194771948719497195071951719527195371954719557195671957719587195971960719617196271963719647196571966719677196871969719707197171972719737197471975719767197771978719797198071981719827198371984719857198671987719887198971990719917199271993719947199571996719977199871999720007200172002720037200472005720067200772008720097201072011720127201372014720157201672017720187201972020720217202272023720247202572026720277202872029720307203172032720337203472035720367203772038720397204072041720427204372044720457204672047720487204972050720517205272053720547205572056720577205872059720607206172062720637206472065720667206772068720697207072071720727207372074720757207672077720787207972080720817208272083720847208572086720877208872089720907209172092720937209472095720967209772098720997210072101721027210372104721057210672107721087210972110721117211272113721147211572116721177211872119721207212172122721237212472125721267212772128721297213072131721327213372134721357213672137721387213972140721417214272143721447214572146721477214872149721507215172152721537215472155721567215772158721597216072161721627216372164721657216672167721687216972170721717217272173721747217572176721777217872179721807218172182721837218472185721867218772188721897219072191721927219372194721957219672197721987219972200722017220272203722047220572206722077220872209722107221172212722137221472215722167221772218722197222072221722227222372224722257222672227722287222972230722317223272233722347223572236722377223872239722407224172242722437224472245722467224772248722497225072251722527225372254722557225672257722587225972260722617226272263722647226572266722677226872269722707227172272722737227472275722767227772278722797228072281722827228372284722857228672287722887228972290722917229272293722947229572296722977229872299723007230172302723037230472305723067230772308723097231072311723127231372314723157231672317723187231972320723217232272323723247232572326723277232872329723307233172332723337233472335723367233772338723397234072341723427234372344723457234672347723487234972350723517235272353723547235572356723577235872359723607236172362723637236472365723667236772368723697237072371723727237372374723757237672377723787237972380723817238272383723847238572386723877238872389723907239172392723937239472395723967239772398723997240072401724027240372404724057240672407724087240972410724117241272413724147241572416724177241872419724207242172422724237242472425724267242772428724297243072431724327243372434724357243672437724387243972440724417244272443724447244572446724477244872449724507245172452724537245472455724567245772458724597246072461724627246372464724657246672467724687246972470724717247272473724747247572476724777247872479724807248172482724837248472485724867248772488724897249072491724927249372494724957249672497724987249972500725017250272503725047250572506725077250872509725107251172512725137251472515725167251772518725197252072521725227252372524725257252672527725287252972530725317253272533725347253572536725377253872539725407254172542725437254472545725467254772548725497255072551725527255372554725557255672557725587255972560725617256272563725647256572566725677256872569725707257172572725737257472575725767257772578725797258072581725827258372584725857258672587725887258972590725917259272593725947259572596725977259872599726007260172602726037260472605726067260772608726097261072611726127261372614726157261672617726187261972620726217262272623726247262572626726277262872629726307263172632726337263472635726367263772638726397264072641726427264372644726457264672647726487264972650726517265272653726547265572656726577265872659726607266172662726637266472665726667266772668726697267072671726727267372674726757267672677726787267972680726817268272683726847268572686726877268872689726907269172692726937269472695726967269772698726997270072701727027270372704727057270672707727087270972710727117271272713727147271572716727177271872719727207272172722727237272472725727267272772728727297273072731727327273372734727357273672737727387273972740727417274272743727447274572746727477274872749727507275172752727537275472755727567275772758727597276072761727627276372764727657276672767727687276972770727717277272773727747277572776727777277872779727807278172782727837278472785727867278772788727897279072791727927279372794727957279672797727987279972800728017280272803728047280572806728077280872809728107281172812728137281472815728167281772818728197282072821728227282372824728257282672827728287282972830728317283272833728347283572836728377283872839728407284172842728437284472845728467284772848728497285072851728527285372854728557285672857728587285972860728617286272863728647286572866728677286872869728707287172872728737287472875728767287772878728797288072881728827288372884728857288672887728887288972890728917289272893728947289572896728977289872899729007290172902729037290472905729067290772908729097291072911729127291372914729157291672917729187291972920729217292272923729247292572926729277292872929729307293172932729337293472935729367293772938729397294072941729427294372944729457294672947729487294972950729517295272953729547295572956729577295872959729607296172962729637296472965729667296772968729697297072971729727297372974729757297672977729787297972980729817298272983729847298572986729877298872989729907299172992729937299472995729967299772998729997300073001730027300373004730057300673007730087300973010730117301273013730147301573016730177301873019730207302173022730237302473025730267302773028730297303073031730327303373034730357303673037730387303973040730417304273043730447304573046730477304873049730507305173052730537305473055730567305773058730597306073061730627306373064730657306673067730687306973070730717307273073730747307573076730777307873079730807308173082730837308473085730867308773088730897309073091730927309373094730957309673097730987309973100731017310273103731047310573106731077310873109731107311173112731137311473115731167311773118731197312073121731227312373124731257312673127731287312973130731317313273133731347313573136731377313873139731407314173142731437314473145731467314773148731497315073151731527315373154731557315673157731587315973160731617316273163731647316573166731677316873169731707317173172731737317473175731767317773178731797318073181731827318373184731857318673187731887318973190731917319273193731947319573196731977319873199732007320173202732037320473205732067320773208732097321073211732127321373214732157321673217732187321973220732217322273223732247322573226732277322873229732307323173232732337323473235732367323773238732397324073241732427324373244732457324673247732487324973250732517325273253732547325573256732577325873259732607326173262732637326473265732667326773268732697327073271732727327373274732757327673277732787327973280732817328273283732847328573286732877328873289732907329173292732937329473295732967329773298732997330073301733027330373304733057330673307733087330973310733117331273313733147331573316733177331873319733207332173322733237332473325733267332773328733297333073331733327333373334733357333673337733387333973340733417334273343733447334573346733477334873349733507335173352733537335473355733567335773358733597336073361733627336373364733657336673367733687336973370733717337273373733747337573376733777337873379733807338173382733837338473385733867338773388733897339073391733927339373394733957339673397733987339973400734017340273403734047340573406734077340873409734107341173412734137341473415734167341773418734197342073421734227342373424734257342673427734287342973430734317343273433734347343573436734377343873439734407344173442734437344473445734467344773448734497345073451734527345373454734557345673457734587345973460734617346273463734647346573466734677346873469734707347173472734737347473475734767347773478734797348073481734827348373484734857348673487734887348973490734917349273493734947349573496734977349873499735007350173502735037350473505735067350773508735097351073511735127351373514735157351673517735187351973520735217352273523735247352573526735277352873529735307353173532735337353473535735367353773538735397354073541735427354373544735457354673547735487354973550735517355273553735547355573556735577355873559735607356173562735637356473565735667356773568735697357073571735727357373574735757357673577735787357973580735817358273583735847358573586735877358873589735907359173592735937359473595735967359773598735997360073601736027360373604736057360673607736087360973610736117361273613736147361573616736177361873619736207362173622736237362473625736267362773628736297363073631736327363373634736357363673637736387363973640736417364273643736447364573646736477364873649736507365173652736537365473655736567365773658736597366073661736627366373664736657366673667736687366973670736717367273673736747367573676736777367873679736807368173682736837368473685736867368773688736897369073691736927369373694736957369673697736987369973700737017370273703737047370573706737077370873709737107371173712737137371473715737167371773718737197372073721737227372373724737257372673727737287372973730737317373273733737347373573736737377373873739737407374173742737437374473745737467374773748737497375073751737527375373754737557375673757737587375973760737617376273763737647376573766737677376873769737707377173772737737377473775737767377773778737797378073781737827378373784737857378673787737887378973790737917379273793737947379573796737977379873799738007380173802738037380473805738067380773808738097381073811738127381373814738157381673817738187381973820738217382273823738247382573826738277382873829738307383173832738337383473835738367383773838738397384073841738427384373844738457384673847738487384973850738517385273853738547385573856738577385873859738607386173862738637386473865738667386773868738697387073871738727387373874738757387673877738787387973880738817388273883738847388573886738877388873889738907389173892738937389473895738967389773898738997390073901739027390373904739057390673907739087390973910739117391273913739147391573916739177391873919739207392173922739237392473925739267392773928739297393073931739327393373934739357393673937739387393973940739417394273943739447394573946739477394873949739507395173952739537395473955739567395773958739597396073961739627396373964739657396673967739687396973970739717397273973739747397573976739777397873979739807398173982739837398473985739867398773988739897399073991739927399373994739957399673997739987399974000740017400274003740047400574006740077400874009740107401174012740137401474015740167401774018740197402074021740227402374024740257402674027740287402974030740317403274033740347403574036740377403874039740407404174042740437404474045740467404774048740497405074051740527405374054740557405674057740587405974060740617406274063740647406574066740677406874069740707407174072740737407474075740767407774078740797408074081740827408374084740857408674087740887408974090740917409274093740947409574096740977409874099741007410174102741037410474105741067410774108741097411074111741127411374114741157411674117741187411974120741217412274123741247412574126741277412874129741307413174132741337413474135741367413774138741397414074141741427414374144741457414674147741487414974150741517415274153741547415574156741577415874159741607416174162741637416474165741667416774168741697417074171741727417374174741757417674177741787417974180741817418274183741847418574186741877418874189741907419174192741937419474195741967419774198741997420074201742027420374204742057420674207742087420974210742117421274213742147421574216742177421874219742207422174222742237422474225742267422774228742297423074231742327423374234742357423674237742387423974240742417424274243742447424574246742477424874249742507425174252742537425474255742567425774258742597426074261742627426374264742657426674267742687426974270742717427274273742747427574276742777427874279742807428174282742837428474285742867428774288742897429074291742927429374294742957429674297742987429974300743017430274303743047430574306743077430874309743107431174312743137431474315743167431774318743197432074321743227432374324743257432674327743287432974330743317433274333743347433574336743377433874339743407434174342743437434474345743467434774348743497435074351743527435374354743557435674357743587435974360743617436274363743647436574366743677436874369743707437174372743737437474375743767437774378743797438074381743827438374384743857438674387743887438974390743917439274393743947439574396743977439874399744007440174402744037440474405744067440774408744097441074411744127441374414744157441674417744187441974420744217442274423744247442574426744277442874429744307443174432744337443474435744367443774438744397444074441744427444374444744457444674447744487444974450744517445274453744547445574456744577445874459744607446174462744637446474465744667446774468744697447074471744727447374474744757447674477744787447974480744817448274483744847448574486744877448874489744907449174492744937449474495744967449774498744997450074501745027450374504745057450674507745087450974510745117451274513745147451574516745177451874519745207452174522745237452474525745267452774528745297453074531745327453374534745357453674537745387453974540745417454274543745447454574546745477454874549745507455174552745537455474555745567455774558745597456074561745627456374564745657456674567745687456974570745717457274573745747457574576745777457874579745807458174582745837458474585745867458774588745897459074591745927459374594745957459674597745987459974600746017460274603746047460574606746077460874609746107461174612746137461474615746167461774618746197462074621746227462374624746257462674627746287462974630746317463274633746347463574636746377463874639746407464174642746437464474645746467464774648746497465074651746527465374654746557465674657746587465974660746617466274663746647466574666746677466874669746707467174672746737467474675746767467774678746797468074681746827468374684746857468674687746887468974690746917469274693746947469574696746977469874699747007470174702747037470474705747067470774708747097471074711747127471374714747157471674717747187471974720747217472274723747247472574726747277472874729747307473174732747337473474735747367473774738747397474074741747427474374744747457474674747747487474974750747517475274753747547475574756747577475874759747607476174762747637476474765747667476774768747697477074771747727477374774747757477674777747787477974780747817478274783747847478574786747877478874789747907479174792747937479474795747967479774798747997480074801748027480374804748057480674807748087480974810748117481274813748147481574816748177481874819748207482174822748237482474825748267482774828748297483074831748327483374834748357483674837748387483974840748417484274843748447484574846748477484874849748507485174852748537485474855748567485774858748597486074861748627486374864748657486674867748687486974870748717487274873748747487574876748777487874879748807488174882748837488474885748867488774888748897489074891748927489374894748957489674897748987489974900749017490274903749047490574906749077490874909749107491174912749137491474915749167491774918749197492074921749227492374924749257492674927749287492974930749317493274933749347493574936749377493874939749407494174942749437494474945749467494774948749497495074951749527495374954749557495674957749587495974960749617496274963749647496574966749677496874969749707497174972749737497474975749767497774978749797498074981749827498374984749857498674987749887498974990749917499274993749947499574996749977499874999750007500175002750037500475005750067500775008750097501075011750127501375014750157501675017750187501975020750217502275023750247502575026750277502875029750307503175032750337503475035750367503775038750397504075041750427504375044750457504675047750487504975050750517505275053750547505575056750577505875059750607506175062750637506475065750667506775068750697507075071750727507375074750757507675077750787507975080750817508275083750847508575086750877508875089750907509175092750937509475095750967509775098750997510075101751027510375104751057510675107751087510975110751117511275113751147511575116751177511875119751207512175122751237512475125751267512775128751297513075131751327513375134751357513675137751387513975140751417514275143751447514575146751477514875149751507515175152751537515475155751567515775158751597516075161751627516375164751657516675167751687516975170751717517275173751747517575176751777517875179751807518175182751837518475185751867518775188751897519075191751927519375194751957519675197751987519975200752017520275203752047520575206752077520875209752107521175212752137521475215752167521775218752197522075221752227522375224752257522675227752287522975230752317523275233752347523575236752377523875239752407524175242752437524475245752467524775248752497525075251752527525375254752557525675257752587525975260752617526275263752647526575266752677526875269752707527175272752737527475275752767527775278752797528075281752827528375284752857528675287752887528975290752917529275293752947529575296752977529875299753007530175302753037530475305753067530775308753097531075311753127531375314753157531675317753187531975320753217532275323753247532575326753277532875329753307533175332753337533475335753367533775338753397534075341753427534375344753457534675347753487534975350753517535275353753547535575356753577535875359753607536175362753637536475365753667536775368753697537075371753727537375374753757537675377753787537975380753817538275383753847538575386753877538875389753907539175392753937539475395753967539775398753997540075401754027540375404754057540675407754087540975410754117541275413754147541575416754177541875419754207542175422754237542475425754267542775428754297543075431754327543375434754357543675437754387543975440754417544275443754447544575446754477544875449754507545175452754537545475455754567545775458754597546075461754627546375464754657546675467754687546975470754717547275473754747547575476754777547875479754807548175482754837548475485754867548775488754897549075491754927549375494754957549675497754987549975500755017550275503755047550575506755077550875509755107551175512755137551475515755167551775518755197552075521755227552375524755257552675527755287552975530755317553275533755347553575536755377553875539755407554175542755437554475545755467554775548755497555075551755527555375554755557555675557755587555975560755617556275563755647556575566755677556875569755707557175572755737557475575755767557775578755797558075581755827558375584755857558675587755887558975590755917559275593755947559575596755977559875599756007560175602756037560475605756067560775608756097561075611756127561375614756157561675617756187561975620756217562275623756247562575626756277562875629756307563175632756337563475635756367563775638756397564075641756427564375644756457564675647756487564975650756517565275653756547565575656756577565875659756607566175662756637566475665756667566775668756697567075671756727567375674756757567675677756787567975680756817568275683756847568575686756877568875689756907569175692756937569475695756967569775698756997570075701757027570375704757057570675707757087570975710757117571275713757147571575716757177571875719757207572175722757237572475725757267572775728757297573075731757327573375734757357573675737757387573975740757417574275743757447574575746757477574875749757507575175752757537575475755757567575775758757597576075761757627576375764757657576675767757687576975770757717577275773757747577575776757777577875779757807578175782757837578475785757867578775788757897579075791757927579375794757957579675797757987579975800758017580275803758047580575806758077580875809758107581175812758137581475815758167581775818758197582075821758227582375824758257582675827758287582975830758317583275833758347583575836758377583875839758407584175842758437584475845758467584775848758497585075851758527585375854758557585675857758587585975860758617586275863758647586575866758677586875869758707587175872758737587475875758767587775878758797588075881758827588375884758857588675887758887588975890758917589275893758947589575896758977589875899759007590175902759037590475905759067590775908759097591075911759127591375914759157591675917759187591975920759217592275923759247592575926759277592875929759307593175932759337593475935759367593775938759397594075941759427594375944759457594675947759487594975950759517595275953759547595575956759577595875959759607596175962759637596475965759667596775968759697597075971759727597375974759757597675977759787597975980759817598275983759847598575986759877598875989759907599175992759937599475995759967599775998759997600076001760027600376004760057600676007760087600976010760117601276013760147601576016760177601876019760207602176022760237602476025760267602776028760297603076031760327603376034760357603676037760387603976040760417604276043760447604576046760477604876049760507605176052760537605476055760567605776058760597606076061760627606376064760657606676067760687606976070760717607276073760747607576076760777607876079760807608176082760837608476085760867608776088760897609076091760927609376094760957609676097760987609976100761017610276103761047610576106761077610876109761107611176112761137611476115761167611776118761197612076121761227612376124761257612676127761287612976130761317613276133761347613576136761377613876139761407614176142761437614476145761467614776148761497615076151761527615376154761557615676157761587615976160761617616276163761647616576166761677616876169761707617176172761737617476175761767617776178761797618076181761827618376184761857618676187761887618976190761917619276193761947619576196761977619876199762007620176202762037620476205762067620776208762097621076211762127621376214762157621676217762187621976220762217622276223762247622576226762277622876229762307623176232762337623476235762367623776238762397624076241762427624376244762457624676247762487624976250762517625276253762547625576256762577625876259762607626176262762637626476265762667626776268762697627076271762727627376274762757627676277762787627976280762817628276283762847628576286762877628876289762907629176292762937629476295762967629776298762997630076301763027630376304763057630676307763087630976310763117631276313763147631576316763177631876319763207632176322763237632476325763267632776328763297633076331763327633376334763357633676337763387633976340763417634276343763447634576346763477634876349763507635176352763537635476355763567635776358763597636076361763627636376364763657636676367763687636976370763717637276373763747637576376763777637876379763807638176382763837638476385763867638776388763897639076391763927639376394763957639676397763987639976400764017640276403764047640576406764077640876409764107641176412764137641476415764167641776418764197642076421764227642376424764257642676427764287642976430764317643276433764347643576436764377643876439764407644176442764437644476445764467644776448764497645076451764527645376454764557645676457764587645976460764617646276463764647646576466764677646876469764707647176472764737647476475764767647776478764797648076481764827648376484764857648676487764887648976490764917649276493764947649576496764977649876499765007650176502765037650476505765067650776508765097651076511765127651376514765157651676517765187651976520765217652276523765247652576526765277652876529765307653176532765337653476535765367653776538765397654076541765427654376544765457654676547765487654976550765517655276553765547655576556765577655876559765607656176562765637656476565765667656776568765697657076571765727657376574765757657676577765787657976580765817658276583765847658576586765877658876589765907659176592765937659476595765967659776598765997660076601766027660376604766057660676607766087660976610766117661276613766147661576616766177661876619766207662176622766237662476625766267662776628766297663076631766327663376634766357663676637766387663976640766417664276643766447664576646766477664876649766507665176652766537665476655766567665776658766597666076661766627666376664766657666676667766687666976670766717667276673766747667576676766777667876679766807668176682766837668476685766867668776688766897669076691766927669376694766957669676697766987669976700767017670276703767047670576706767077670876709767107671176712767137671476715767167671776718767197672076721767227672376724767257672676727767287672976730767317673276733767347673576736767377673876739767407674176742767437674476745767467674776748767497675076751767527675376754767557675676757767587675976760767617676276763767647676576766767677676876769767707677176772767737677476775767767677776778767797678076781767827678376784767857678676787767887678976790767917679276793767947679576796767977679876799768007680176802768037680476805768067680776808768097681076811768127681376814768157681676817768187681976820768217682276823768247682576826768277682876829768307683176832768337683476835768367683776838768397684076841768427684376844768457684676847768487684976850768517685276853768547685576856768577685876859768607686176862768637686476865768667686776868768697687076871768727687376874768757687676877768787687976880768817688276883768847688576886768877688876889768907689176892768937689476895768967689776898768997690076901769027690376904769057690676907769087690976910769117691276913769147691576916769177691876919769207692176922769237692476925769267692776928769297693076931769327693376934769357693676937769387693976940769417694276943769447694576946769477694876949769507695176952769537695476955769567695776958769597696076961769627696376964769657696676967769687696976970769717697276973769747697576976769777697876979769807698176982769837698476985769867698776988769897699076991769927699376994769957699676997769987699977000770017700277003770047700577006770077700877009770107701177012770137701477015770167701777018770197702077021770227702377024770257702677027770287702977030770317703277033770347703577036770377703877039770407704177042770437704477045770467704777048770497705077051770527705377054770557705677057770587705977060770617706277063770647706577066770677706877069770707707177072770737707477075770767707777078770797708077081770827708377084770857708677087770887708977090770917709277093770947709577096770977709877099771007710177102771037710477105771067710777108771097711077111771127711377114771157711677117771187711977120771217712277123771247712577126771277712877129771307713177132771337713477135771367713777138771397714077141771427714377144771457714677147771487714977150771517715277153771547715577156771577715877159771607716177162771637716477165771667716777168771697717077171771727717377174771757717677177771787717977180771817718277183771847718577186771877718877189771907719177192771937719477195771967719777198771997720077201772027720377204772057720677207772087720977210772117721277213772147721577216772177721877219772207722177222772237722477225772267722777228772297723077231772327723377234772357723677237772387723977240772417724277243772447724577246772477724877249772507725177252772537725477255772567725777258772597726077261772627726377264772657726677267772687726977270772717727277273772747727577276772777727877279772807728177282772837728477285772867728777288772897729077291772927729377294772957729677297772987729977300773017730277303773047730577306773077730877309773107731177312773137731477315773167731777318773197732077321773227732377324773257732677327773287732977330773317733277333773347733577336773377733877339773407734177342773437734477345773467734777348773497735077351773527735377354773557735677357773587735977360773617736277363773647736577366773677736877369773707737177372773737737477375773767737777378773797738077381773827738377384773857738677387773887738977390773917739277393773947739577396773977739877399774007740177402774037740477405774067740777408774097741077411774127741377414774157741677417774187741977420774217742277423774247742577426774277742877429774307743177432774337743477435774367743777438774397744077441774427744377444774457744677447774487744977450774517745277453774547745577456774577745877459774607746177462774637746477465774667746777468774697747077471774727747377474774757747677477774787747977480774817748277483774847748577486774877748877489774907749177492774937749477495774967749777498774997750077501775027750377504775057750677507775087750977510775117751277513775147751577516775177751877519775207752177522775237752477525775267752777528775297753077531775327753377534775357753677537775387753977540775417754277543775447754577546775477754877549775507755177552775537755477555775567755777558775597756077561775627756377564775657756677567775687756977570775717757277573775747757577576775777757877579775807758177582775837758477585775867758777588775897759077591775927759377594775957759677597775987759977600776017760277603776047760577606776077760877609776107761177612776137761477615776167761777618776197762077621776227762377624776257762677627776287762977630776317763277633776347763577636776377763877639776407764177642776437764477645776467764777648776497765077651776527765377654776557765677657776587765977660776617766277663776647766577666776677766877669776707767177672776737767477675776767767777678776797768077681776827768377684776857768677687776887768977690776917769277693776947769577696776977769877699777007770177702777037770477705777067770777708777097771077711777127771377714777157771677717777187771977720777217772277723777247772577726777277772877729777307773177732777337773477735777367773777738777397774077741777427774377744777457774677747777487774977750777517775277753777547775577756777577775877759777607776177762777637776477765777667776777768777697777077771777727777377774777757777677777777787777977780777817778277783777847778577786777877778877789777907779177792777937779477795777967779777798777997780077801778027780377804778057780677807778087780977810778117781277813778147781577816778177781877819778207782177822778237782477825778267782777828778297783077831778327783377834778357783677837778387783977840778417784277843778447784577846778477784877849778507785177852778537785477855778567785777858778597786077861778627786377864778657786677867778687786977870778717787277873778747787577876778777787877879778807788177882778837788477885778867788777888778897789077891778927789377894778957789677897778987789977900779017790277903779047790577906779077790877909779107791177912779137791477915779167791777918779197792077921779227792377924779257792677927779287792977930779317793277933779347793577936779377793877939779407794177942779437794477945779467794777948779497795077951779527795377954779557795677957779587795977960779617796277963779647796577966779677796877969779707797177972779737797477975779767797777978779797798077981779827798377984779857798677987779887798977990779917799277993779947799577996779977799877999780007800178002780037800478005780067800778008780097801078011780127801378014780157801678017780187801978020780217802278023780247802578026780277802878029780307803178032780337803478035780367803778038780397804078041780427804378044780457804678047780487804978050780517805278053780547805578056780577805878059780607806178062780637806478065780667806778068780697807078071780727807378074780757807678077780787807978080780817808278083780847808578086780877808878089780907809178092780937809478095780967809778098780997810078101781027810378104781057810678107781087810978110781117811278113781147811578116781177811878119781207812178122781237812478125781267812778128781297813078131781327813378134781357813678137781387813978140781417814278143781447814578146781477814878149781507815178152781537815478155781567815778158781597816078161781627816378164781657816678167781687816978170781717817278173781747817578176781777817878179781807818178182781837818478185781867818778188781897819078191781927819378194781957819678197781987819978200782017820278203782047820578206782077820878209782107821178212782137821478215782167821778218782197822078221782227822378224782257822678227782287822978230782317823278233782347823578236782377823878239782407824178242782437824478245782467824778248782497825078251782527825378254782557825678257782587825978260782617826278263782647826578266782677826878269782707827178272782737827478275782767827778278782797828078281782827828378284782857828678287782887828978290782917829278293782947829578296782977829878299783007830178302783037830478305783067830778308783097831078311783127831378314783157831678317783187831978320783217832278323783247832578326783277832878329783307833178332783337833478335783367833778338783397834078341783427834378344783457834678347783487834978350783517835278353783547835578356783577835878359783607836178362783637836478365783667836778368783697837078371783727837378374783757837678377783787837978380783817838278383783847838578386783877838878389783907839178392783937839478395783967839778398783997840078401784027840378404784057840678407784087840978410784117841278413784147841578416784177841878419784207842178422784237842478425784267842778428784297843078431784327843378434784357843678437784387843978440784417844278443784447844578446784477844878449784507845178452784537845478455784567845778458784597846078461784627846378464784657846678467784687846978470784717847278473784747847578476784777847878479784807848178482784837848478485784867848778488784897849078491784927849378494784957849678497784987849978500785017850278503785047850578506785077850878509785107851178512785137851478515785167851778518785197852078521785227852378524785257852678527785287852978530785317853278533785347853578536785377853878539785407854178542785437854478545785467854778548785497855078551785527855378554785557855678557785587855978560785617856278563785647856578566785677856878569785707857178572785737857478575785767857778578785797858078581785827858378584785857858678587785887858978590785917859278593785947859578596785977859878599786007860178602786037860478605786067860778608786097861078611786127861378614786157861678617786187861978620786217862278623786247862578626786277862878629786307863178632786337863478635786367863778638786397864078641786427864378644786457864678647786487864978650786517865278653786547865578656786577865878659786607866178662786637866478665786667866778668786697867078671786727867378674786757867678677786787867978680786817868278683786847868578686786877868878689786907869178692786937869478695786967869778698786997870078701787027870378704787057870678707787087870978710787117871278713787147871578716787177871878719787207872178722787237872478725787267872778728787297873078731787327873378734787357873678737787387873978740787417874278743787447874578746787477874878749787507875178752787537875478755787567875778758787597876078761787627876378764787657876678767787687876978770787717877278773787747877578776787777877878779787807878178782787837878478785787867878778788787897879078791787927879378794787957879678797787987879978800788017880278803788047880578806788077880878809788107881178812788137881478815788167881778818788197882078821788227882378824788257882678827788287882978830788317883278833788347883578836788377883878839788407884178842788437884478845788467884778848788497885078851788527885378854788557885678857788587885978860788617886278863788647886578866788677886878869788707887178872788737887478875788767887778878788797888078881788827888378884788857888678887788887888978890788917889278893788947889578896788977889878899789007890178902789037890478905789067890778908789097891078911789127891378914789157891678917789187891978920789217892278923789247892578926789277892878929789307893178932789337893478935789367893778938789397894078941789427894378944789457894678947789487894978950789517895278953789547895578956789577895878959789607896178962789637896478965789667896778968789697897078971789727897378974789757897678977789787897978980789817898278983789847898578986789877898878989789907899178992789937899478995789967899778998789997900079001790027900379004790057900679007790087900979010790117901279013790147901579016790177901879019790207902179022790237902479025790267902779028790297903079031790327903379034790357903679037790387903979040790417904279043790447904579046790477904879049790507905179052790537905479055790567905779058790597906079061790627906379064790657906679067790687906979070790717907279073790747907579076790777907879079790807908179082790837908479085790867908779088790897909079091790927909379094790957909679097790987909979100791017910279103791047910579106791077910879109791107911179112791137911479115791167911779118791197912079121791227912379124791257912679127791287912979130791317913279133791347913579136791377913879139791407914179142791437914479145791467914779148791497915079151791527915379154791557915679157791587915979160791617916279163791647916579166791677916879169791707917179172791737917479175791767917779178791797918079181791827918379184791857918679187791887918979190791917919279193791947919579196791977919879199792007920179202792037920479205792067920779208792097921079211792127921379214792157921679217792187921979220792217922279223792247922579226792277922879229792307923179232792337923479235792367923779238792397924079241792427924379244792457924679247792487924979250792517925279253792547925579256792577925879259792607926179262792637926479265792667926779268792697927079271792727927379274792757927679277792787927979280792817928279283792847928579286792877928879289792907929179292792937929479295792967929779298792997930079301793027930379304793057930679307793087930979310793117931279313793147931579316793177931879319793207932179322793237932479325793267932779328793297933079331793327933379334793357933679337793387933979340793417934279343793447934579346793477934879349793507935179352793537935479355793567935779358793597936079361793627936379364793657936679367793687936979370793717937279373793747937579376793777937879379793807938179382793837938479385793867938779388793897939079391793927939379394793957939679397793987939979400794017940279403794047940579406794077940879409794107941179412794137941479415794167941779418794197942079421794227942379424794257942679427794287942979430794317943279433794347943579436794377943879439794407944179442794437944479445794467944779448794497945079451794527945379454794557945679457794587945979460794617946279463794647946579466794677946879469794707947179472794737947479475794767947779478794797948079481794827948379484794857948679487794887948979490794917949279493794947949579496794977949879499795007950179502795037950479505795067950779508795097951079511795127951379514795157951679517795187951979520795217952279523795247952579526795277952879529795307953179532795337953479535795367953779538795397954079541795427954379544795457954679547795487954979550795517955279553795547955579556795577955879559795607956179562795637956479565795667956779568795697957079571795727957379574795757957679577795787957979580795817958279583795847958579586795877958879589795907959179592795937959479595795967959779598795997960079601796027960379604796057960679607796087960979610796117961279613796147961579616796177961879619796207962179622796237962479625796267962779628796297963079631796327963379634796357963679637796387963979640796417964279643796447964579646796477964879649796507965179652796537965479655796567965779658796597966079661796627966379664796657966679667796687966979670796717967279673796747967579676796777967879679796807968179682796837968479685796867968779688796897969079691796927969379694796957969679697796987969979700797017970279703797047970579706797077970879709797107971179712797137971479715797167971779718797197972079721797227972379724797257972679727797287972979730797317973279733797347973579736797377973879739797407974179742797437974479745797467974779748797497975079751797527975379754797557975679757797587975979760797617976279763797647976579766797677976879769797707977179772797737977479775797767977779778797797978079781797827978379784797857978679787797887978979790797917979279793797947979579796797977979879799798007980179802798037980479805798067980779808798097981079811798127981379814798157981679817798187981979820798217982279823798247982579826798277982879829798307983179832798337983479835798367983779838798397984079841798427984379844798457984679847798487984979850798517985279853798547985579856798577985879859798607986179862798637986479865798667986779868798697987079871798727987379874798757987679877798787987979880798817988279883798847988579886798877988879889798907989179892798937989479895798967989779898798997990079901799027990379904799057990679907799087990979910799117991279913799147991579916799177991879919799207992179922799237992479925799267992779928799297993079931799327993379934799357993679937799387993979940799417994279943799447994579946799477994879949799507995179952799537995479955799567995779958799597996079961799627996379964799657996679967799687996979970799717997279973799747997579976799777997879979799807998179982799837998479985799867998779988799897999079991799927999379994799957999679997799987999980000800018000280003800048000580006800078000880009800108001180012800138001480015800168001780018800198002080021800228002380024800258002680027800288002980030800318003280033800348003580036800378003880039800408004180042800438004480045800468004780048800498005080051800528005380054800558005680057800588005980060800618006280063800648006580066800678006880069800708007180072800738007480075800768007780078800798008080081800828008380084800858008680087800888008980090800918009280093800948009580096800978009880099801008010180102801038010480105801068010780108801098011080111801128011380114801158011680117801188011980120801218012280123801248012580126801278012880129801308013180132801338013480135801368013780138801398014080141801428014380144801458014680147801488014980150801518015280153801548015580156801578015880159801608016180162801638016480165801668016780168801698017080171801728017380174801758017680177801788017980180801818018280183801848018580186801878018880189801908019180192801938019480195801968019780198801998020080201802028020380204802058020680207802088020980210802118021280213802148021580216802178021880219802208022180222802238022480225802268022780228802298023080231802328023380234802358023680237802388023980240802418024280243802448024580246802478024880249802508025180252802538025480255802568025780258802598026080261802628026380264802658026680267802688026980270802718027280273802748027580276802778027880279802808028180282802838028480285802868028780288802898029080291802928029380294802958029680297802988029980300803018030280303803048030580306803078030880309803108031180312803138031480315803168031780318803198032080321803228032380324803258032680327803288032980330803318033280333803348033580336803378033880339803408034180342803438034480345803468034780348803498035080351803528035380354803558035680357803588035980360803618036280363803648036580366803678036880369803708037180372803738037480375803768037780378803798038080381803828038380384803858038680387803888038980390803918039280393803948039580396803978039880399804008040180402804038040480405804068040780408804098041080411804128041380414804158041680417804188041980420804218042280423804248042580426804278042880429804308043180432804338043480435804368043780438804398044080441804428044380444804458044680447804488044980450804518045280453804548045580456804578045880459804608046180462804638046480465804668046780468804698047080471804728047380474804758047680477804788047980480804818048280483804848048580486804878048880489804908049180492804938049480495804968049780498804998050080501805028050380504805058050680507805088050980510805118051280513805148051580516805178051880519805208052180522805238052480525805268052780528805298053080531805328053380534805358053680537805388053980540805418054280543805448054580546805478054880549805508055180552805538055480555805568055780558805598056080561805628056380564805658056680567805688056980570805718057280573805748057580576805778057880579805808058180582805838058480585805868058780588805898059080591805928059380594805958059680597805988059980600806018060280603806048060580606806078060880609806108061180612806138061480615806168061780618806198062080621806228062380624806258062680627806288062980630806318063280633806348063580636806378063880639806408064180642806438064480645806468064780648806498065080651806528065380654806558065680657806588065980660806618066280663806648066580666806678066880669806708067180672806738067480675806768067780678806798068080681806828068380684806858068680687806888068980690806918069280693806948069580696806978069880699807008070180702807038070480705807068070780708807098071080711807128071380714807158071680717807188071980720807218072280723807248072580726807278072880729807308073180732807338073480735807368073780738807398074080741807428074380744807458074680747807488074980750807518075280753807548075580756807578075880759807608076180762807638076480765807668076780768807698077080771807728077380774807758077680777807788077980780807818078280783807848078580786807878078880789807908079180792807938079480795807968079780798807998080080801808028080380804808058080680807808088080980810808118081280813808148081580816808178081880819808208082180822808238082480825808268082780828808298083080831808328083380834808358083680837808388083980840808418084280843808448084580846808478084880849808508085180852808538085480855808568085780858808598086080861808628086380864808658086680867808688086980870808718087280873808748087580876808778087880879808808088180882808838088480885808868088780888808898089080891808928089380894808958089680897808988089980900809018090280903809048090580906809078090880909809108091180912809138091480915809168091780918809198092080921809228092380924809258092680927809288092980930809318093280933809348093580936809378093880939809408094180942809438094480945809468094780948809498095080951809528095380954809558095680957809588095980960809618096280963809648096580966809678096880969809708097180972809738097480975809768097780978809798098080981809828098380984809858098680987809888098980990809918099280993809948099580996809978099880999810008100181002810038100481005810068100781008810098101081011810128101381014810158101681017810188101981020810218102281023810248102581026810278102881029810308103181032810338103481035810368103781038810398104081041810428104381044810458104681047810488104981050810518105281053810548105581056810578105881059810608106181062810638106481065810668106781068810698107081071810728107381074810758107681077810788107981080810818108281083810848108581086810878108881089810908109181092810938109481095810968109781098810998110081101811028110381104811058110681107811088110981110811118111281113811148111581116811178111881119811208112181122811238112481125811268112781128811298113081131811328113381134811358113681137811388113981140811418114281143811448114581146811478114881149811508115181152811538115481155811568115781158811598116081161811628116381164811658116681167811688116981170811718117281173811748117581176811778117881179811808118181182811838118481185811868118781188811898119081191811928119381194811958119681197811988119981200812018120281203812048120581206812078120881209812108121181212812138121481215812168121781218812198122081221812228122381224812258122681227812288122981230812318123281233812348123581236812378123881239812408124181242812438124481245812468124781248812498125081251812528125381254812558125681257812588125981260812618126281263812648126581266812678126881269812708127181272812738127481275812768127781278812798128081281812828128381284812858128681287812888128981290812918129281293812948129581296812978129881299813008130181302813038130481305813068130781308813098131081311813128131381314813158131681317813188131981320813218132281323813248132581326813278132881329813308133181332813338133481335813368133781338813398134081341813428134381344813458134681347813488134981350813518135281353813548135581356813578135881359813608136181362813638136481365813668136781368813698137081371813728137381374813758137681377813788137981380813818138281383813848138581386813878138881389813908139181392813938139481395813968139781398813998140081401814028140381404814058140681407814088140981410814118141281413814148141581416814178141881419814208142181422814238142481425814268142781428
  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. //# sourceMappingURL=babylon.types.js.map
  18. var BABYLON;
  19. (function (BABYLON) {
  20. var KeyboardEventTypes = /** @class */ (function () {
  21. function KeyboardEventTypes() {
  22. }
  23. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  24. get: function () {
  25. return KeyboardEventTypes._KEYDOWN;
  26. },
  27. enumerable: true,
  28. configurable: true
  29. });
  30. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  31. get: function () {
  32. return KeyboardEventTypes._KEYUP;
  33. },
  34. enumerable: true,
  35. configurable: true
  36. });
  37. KeyboardEventTypes._KEYDOWN = 0x01;
  38. KeyboardEventTypes._KEYUP = 0x02;
  39. return KeyboardEventTypes;
  40. }());
  41. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  42. var KeyboardInfo = /** @class */ (function () {
  43. function KeyboardInfo(type, event) {
  44. this.type = type;
  45. this.event = event;
  46. }
  47. return KeyboardInfo;
  48. }());
  49. BABYLON.KeyboardInfo = KeyboardInfo;
  50. /**
  51. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  52. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  53. */
  54. var KeyboardInfoPre = /** @class */ (function (_super) {
  55. __extends(KeyboardInfoPre, _super);
  56. function KeyboardInfoPre(type, event) {
  57. var _this = _super.call(this, type, event) || this;
  58. _this.skipOnPointerObservable = false;
  59. return _this;
  60. }
  61. return KeyboardInfoPre;
  62. }(KeyboardInfo));
  63. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  64. })(BABYLON || (BABYLON = {}));
  65. //# sourceMappingURL=babylon.keyboardEvents.js.map
  66. var BABYLON;
  67. (function (BABYLON) {
  68. var PointerEventTypes = /** @class */ (function () {
  69. function PointerEventTypes() {
  70. }
  71. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  72. get: function () {
  73. return PointerEventTypes._POINTERDOWN;
  74. },
  75. enumerable: true,
  76. configurable: true
  77. });
  78. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  79. get: function () {
  80. return PointerEventTypes._POINTERUP;
  81. },
  82. enumerable: true,
  83. configurable: true
  84. });
  85. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  86. get: function () {
  87. return PointerEventTypes._POINTERMOVE;
  88. },
  89. enumerable: true,
  90. configurable: true
  91. });
  92. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  93. get: function () {
  94. return PointerEventTypes._POINTERWHEEL;
  95. },
  96. enumerable: true,
  97. configurable: true
  98. });
  99. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  100. get: function () {
  101. return PointerEventTypes._POINTERPICK;
  102. },
  103. enumerable: true,
  104. configurable: true
  105. });
  106. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  107. get: function () {
  108. return PointerEventTypes._POINTERTAP;
  109. },
  110. enumerable: true,
  111. configurable: true
  112. });
  113. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  114. get: function () {
  115. return PointerEventTypes._POINTERDOUBLETAP;
  116. },
  117. enumerable: true,
  118. configurable: true
  119. });
  120. PointerEventTypes._POINTERDOWN = 0x01;
  121. PointerEventTypes._POINTERUP = 0x02;
  122. PointerEventTypes._POINTERMOVE = 0x04;
  123. PointerEventTypes._POINTERWHEEL = 0x08;
  124. PointerEventTypes._POINTERPICK = 0x10;
  125. PointerEventTypes._POINTERTAP = 0x20;
  126. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  127. return PointerEventTypes;
  128. }());
  129. BABYLON.PointerEventTypes = PointerEventTypes;
  130. var PointerInfoBase = /** @class */ (function () {
  131. function PointerInfoBase(type, event) {
  132. this.type = type;
  133. this.event = event;
  134. }
  135. return PointerInfoBase;
  136. }());
  137. BABYLON.PointerInfoBase = PointerInfoBase;
  138. /**
  139. * This class is used to store pointer related info for the onPrePointerObservable event.
  140. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  141. */
  142. var PointerInfoPre = /** @class */ (function (_super) {
  143. __extends(PointerInfoPre, _super);
  144. function PointerInfoPre(type, event, localX, localY) {
  145. var _this = _super.call(this, type, event) || this;
  146. _this.skipOnPointerObservable = false;
  147. _this.localPosition = new BABYLON.Vector2(localX, localY);
  148. return _this;
  149. }
  150. return PointerInfoPre;
  151. }(PointerInfoBase));
  152. BABYLON.PointerInfoPre = PointerInfoPre;
  153. /**
  154. * This type contains all the data related to a pointer event in Babylon.js.
  155. * 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.
  156. */
  157. var PointerInfo = /** @class */ (function (_super) {
  158. __extends(PointerInfo, _super);
  159. function PointerInfo(type, event, pickInfo) {
  160. var _this = _super.call(this, type, event) || this;
  161. _this.pickInfo = pickInfo;
  162. return _this;
  163. }
  164. return PointerInfo;
  165. }(PointerInfoBase));
  166. BABYLON.PointerInfo = PointerInfo;
  167. })(BABYLON || (BABYLON = {}));
  168. //# sourceMappingURL=babylon.pointerEvents.js.map
  169. var BABYLON;
  170. (function (BABYLON) {
  171. BABYLON.ToGammaSpace = 1 / 2.2;
  172. BABYLON.ToLinearSpace = 2.2;
  173. BABYLON.Epsilon = 0.001;
  174. var Color3 = /** @class */ (function () {
  175. /**
  176. * Creates a new Color3 object from red, green, blue values, all between 0 and 1.
  177. */
  178. function Color3(r, g, b) {
  179. if (r === void 0) { r = 0; }
  180. if (g === void 0) { g = 0; }
  181. if (b === void 0) { b = 0; }
  182. this.r = r;
  183. this.g = g;
  184. this.b = b;
  185. }
  186. /**
  187. * Returns a string with the Color3 current values.
  188. */
  189. Color3.prototype.toString = function () {
  190. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  191. };
  192. /**
  193. * Returns the string "Color3".
  194. */
  195. Color3.prototype.getClassName = function () {
  196. return "Color3";
  197. };
  198. /**
  199. * Returns the Color3 hash code.
  200. */
  201. Color3.prototype.getHashCode = function () {
  202. var hash = this.r || 0;
  203. hash = (hash * 397) ^ (this.g || 0);
  204. hash = (hash * 397) ^ (this.b || 0);
  205. return hash;
  206. };
  207. // Operators
  208. /**
  209. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements.
  210. * Returns the Color3.
  211. */
  212. Color3.prototype.toArray = function (array, index) {
  213. if (index === undefined) {
  214. index = 0;
  215. }
  216. array[index] = this.r;
  217. array[index + 1] = this.g;
  218. array[index + 2] = this.b;
  219. return this;
  220. };
  221. /**
  222. * Returns a new Color4 object from the current Color3 and the passed alpha.
  223. */
  224. Color3.prototype.toColor4 = function (alpha) {
  225. if (alpha === void 0) { alpha = 1; }
  226. return new Color4(this.r, this.g, this.b, alpha);
  227. };
  228. /**
  229. * Returns a new array populated with 3 numeric elements : red, green and blue values.
  230. */
  231. Color3.prototype.asArray = function () {
  232. var result = new Array();
  233. this.toArray(result, 0);
  234. return result;
  235. };
  236. /**
  237. * Returns the luminance value (float).
  238. */
  239. Color3.prototype.toLuminance = function () {
  240. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  241. };
  242. /**
  243. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object.
  244. * Returns this new object.
  245. */
  246. Color3.prototype.multiply = function (otherColor) {
  247. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  248. };
  249. /**
  250. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result".
  251. * Returns the current Color3.
  252. */
  253. Color3.prototype.multiplyToRef = function (otherColor, result) {
  254. result.r = this.r * otherColor.r;
  255. result.g = this.g * otherColor.g;
  256. result.b = this.b * otherColor.b;
  257. return this;
  258. };
  259. /**
  260. * Boolean : True if the rgb values are equal to the passed ones.
  261. */
  262. Color3.prototype.equals = function (otherColor) {
  263. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  264. };
  265. /**
  266. * Boolean : True if the rgb values are equal to the passed ones.
  267. */
  268. Color3.prototype.equalsFloats = function (r, g, b) {
  269. return this.r === r && this.g === g && this.b === b;
  270. };
  271. /**
  272. * Multiplies in place each rgb value by scale.
  273. * Returns the updated Color3.
  274. */
  275. Color3.prototype.scale = function (scale) {
  276. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  277. };
  278. /**
  279. * Multiplies the rgb values by scale and stores the result into "result".
  280. * Returns the unmodified current Color3.
  281. */
  282. Color3.prototype.scaleToRef = function (scale, result) {
  283. result.r = this.r * scale;
  284. result.g = this.g * scale;
  285. result.b = this.b * scale;
  286. return this;
  287. };
  288. /**
  289. * Returns a new Color3 set with the added values of the current Color3 and of the passed one.
  290. */
  291. Color3.prototype.add = function (otherColor) {
  292. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  293. };
  294. /**
  295. * Stores the result of the addition of the current Color3 and passed one rgb values into "result".
  296. * Returns the unmodified current Color3.
  297. */
  298. Color3.prototype.addToRef = function (otherColor, result) {
  299. result.r = this.r + otherColor.r;
  300. result.g = this.g + otherColor.g;
  301. result.b = this.b + otherColor.b;
  302. return this;
  303. };
  304. /**
  305. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3 .
  306. */
  307. Color3.prototype.subtract = function (otherColor) {
  308. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  309. };
  310. /**
  311. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result".
  312. * Returns the unmodified current Color3.
  313. */
  314. Color3.prototype.subtractToRef = function (otherColor, result) {
  315. result.r = this.r - otherColor.r;
  316. result.g = this.g - otherColor.g;
  317. result.b = this.b - otherColor.b;
  318. return this;
  319. };
  320. /**
  321. * Returns a new Color3 copied the current one.
  322. */
  323. Color3.prototype.clone = function () {
  324. return new Color3(this.r, this.g, this.b);
  325. };
  326. /**
  327. * Copies the rgb values from the source in the current Color3.
  328. * Returns the updated Color3.
  329. */
  330. Color3.prototype.copyFrom = function (source) {
  331. this.r = source.r;
  332. this.g = source.g;
  333. this.b = source.b;
  334. return this;
  335. };
  336. /**
  337. * Updates the Color3 rgb values from the passed floats.
  338. * Returns the Color3.
  339. */
  340. Color3.prototype.copyFromFloats = function (r, g, b) {
  341. this.r = r;
  342. this.g = g;
  343. this.b = b;
  344. return this;
  345. };
  346. /**
  347. * Updates the Color3 rgb values from the passed floats.
  348. * Returns the Color3.
  349. */
  350. Color3.prototype.set = function (r, g, b) {
  351. return this.copyFromFloats(r, g, b);
  352. };
  353. /**
  354. * Returns the Color3 hexadecimal code as a string.
  355. */
  356. Color3.prototype.toHexString = function () {
  357. var intR = (this.r * 255) | 0;
  358. var intG = (this.g * 255) | 0;
  359. var intB = (this.b * 255) | 0;
  360. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  361. };
  362. /**
  363. * Returns a new Color3 converted to linear space.
  364. */
  365. Color3.prototype.toLinearSpace = function () {
  366. var convertedColor = new Color3();
  367. this.toLinearSpaceToRef(convertedColor);
  368. return convertedColor;
  369. };
  370. /**
  371. * Converts the Color3 values to linear space and stores the result in "convertedColor".
  372. * Returns the unmodified Color3.
  373. */
  374. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  375. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  376. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  377. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  378. return this;
  379. };
  380. /**
  381. * Returns a new Color3 converted to gamma space.
  382. */
  383. Color3.prototype.toGammaSpace = function () {
  384. var convertedColor = new Color3();
  385. this.toGammaSpaceToRef(convertedColor);
  386. return convertedColor;
  387. };
  388. /**
  389. * Converts the Color3 values to gamma space and stores the result in "convertedColor".
  390. * Returns the unmodified Color3.
  391. */
  392. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  393. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  394. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  395. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  396. return this;
  397. };
  398. // Statics
  399. /**
  400. * Creates a new Color3 from the string containing valid hexadecimal values.
  401. */
  402. Color3.FromHexString = function (hex) {
  403. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  404. //Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  405. return new Color3(0, 0, 0);
  406. }
  407. var r = parseInt(hex.substring(1, 3), 16);
  408. var g = parseInt(hex.substring(3, 5), 16);
  409. var b = parseInt(hex.substring(5, 7), 16);
  410. return Color3.FromInts(r, g, b);
  411. };
  412. /**
  413. * Creates a new Vector3 from the startind index of the passed array.
  414. */
  415. Color3.FromArray = function (array, offset) {
  416. if (offset === void 0) { offset = 0; }
  417. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  418. };
  419. /**
  420. * Creates a new Color3 from integer values ( < 256).
  421. */
  422. Color3.FromInts = function (r, g, b) {
  423. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  424. };
  425. /**
  426. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3.
  427. */
  428. Color3.Lerp = function (start, end, amount) {
  429. var r = start.r + ((end.r - start.r) * amount);
  430. var g = start.g + ((end.g - start.g) * amount);
  431. var b = start.b + ((end.b - start.b) * amount);
  432. return new Color3(r, g, b);
  433. };
  434. Color3.Red = function () { return new Color3(1, 0, 0); };
  435. Color3.Green = function () { return new Color3(0, 1, 0); };
  436. Color3.Blue = function () { return new Color3(0, 0, 1); };
  437. Color3.Black = function () { return new Color3(0, 0, 0); };
  438. Color3.White = function () { return new Color3(1, 1, 1); };
  439. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  440. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  441. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  442. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  443. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  444. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  445. return Color3;
  446. }());
  447. BABYLON.Color3 = Color3;
  448. var Color4 = /** @class */ (function () {
  449. /**
  450. * Creates a new Color4 object from the passed float values ( < 1) : red, green, blue, alpha.
  451. */
  452. function Color4(r, g, b, a) {
  453. if (r === void 0) { r = 0; }
  454. if (g === void 0) { g = 0; }
  455. if (b === void 0) { b = 0; }
  456. if (a === void 0) { a = 1; }
  457. this.r = r;
  458. this.g = g;
  459. this.b = b;
  460. this.a = a;
  461. }
  462. // Operators
  463. /**
  464. * Adds in place the passed Color4 values to the current Color4.
  465. * Returns the updated Color4.
  466. */
  467. Color4.prototype.addInPlace = function (right) {
  468. this.r += right.r;
  469. this.g += right.g;
  470. this.b += right.b;
  471. this.a += right.a;
  472. return this;
  473. };
  474. /**
  475. * Returns a new array populated with 4 numeric elements : red, green, blue, alpha values.
  476. */
  477. Color4.prototype.asArray = function () {
  478. var result = new Array();
  479. this.toArray(result, 0);
  480. return result;
  481. };
  482. /**
  483. * Stores from the starting index in the passed array the Color4 successive values.
  484. * Returns the Color4.
  485. */
  486. Color4.prototype.toArray = function (array, index) {
  487. if (index === undefined) {
  488. index = 0;
  489. }
  490. array[index] = this.r;
  491. array[index + 1] = this.g;
  492. array[index + 2] = this.b;
  493. array[index + 3] = this.a;
  494. return this;
  495. };
  496. /**
  497. * Returns a new Color4 set with the added values of the current Color4 and of the passed one.
  498. */
  499. Color4.prototype.add = function (right) {
  500. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  501. };
  502. /**
  503. * Returns a new Color4 set with the subtracted values of the passed one from the current Color4.
  504. */
  505. Color4.prototype.subtract = function (right) {
  506. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  507. };
  508. /**
  509. * Subtracts the passed ones from the current Color4 values and stores the results in "result".
  510. * Returns the Color4.
  511. */
  512. Color4.prototype.subtractToRef = function (right, result) {
  513. result.r = this.r - right.r;
  514. result.g = this.g - right.g;
  515. result.b = this.b - right.b;
  516. result.a = this.a - right.a;
  517. return this;
  518. };
  519. /**
  520. * Creates a new Color4 with the current Color4 values multiplied by scale.
  521. */
  522. Color4.prototype.scale = function (scale) {
  523. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  524. };
  525. /**
  526. * Multiplies the current Color4 values by scale and stores the result in "result".
  527. * Returns the Color4.
  528. */
  529. Color4.prototype.scaleToRef = function (scale, result) {
  530. result.r = this.r * scale;
  531. result.g = this.g * scale;
  532. result.b = this.b * scale;
  533. result.a = this.a * scale;
  534. return this;
  535. };
  536. /**
  537. * Multipy an RGBA Color4 value by another and return a new Color4 object
  538. * @param color The Color4 (RGBA) value to multiply by
  539. * @returns A new Color4.
  540. */
  541. Color4.prototype.multiply = function (color) {
  542. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  543. };
  544. /**
  545. * Multipy an RGBA Color4 value by another and push the result in a reference value
  546. * @param color The Color4 (RGBA) value to multiply by
  547. * @param result The Color4 (RGBA) to fill the result in
  548. * @returns the result Color4.
  549. */
  550. Color4.prototype.multiplyToRef = function (color, result) {
  551. result.r = this.r * color.r;
  552. result.g = this.g * color.g;
  553. result.b = this.b * color.b;
  554. result.a = this.a * color.a;
  555. return result;
  556. };
  557. /**
  558. * Returns a string with the Color4 values.
  559. */
  560. Color4.prototype.toString = function () {
  561. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  562. };
  563. /**
  564. * Returns the string "Color4"
  565. */
  566. Color4.prototype.getClassName = function () {
  567. return "Color4";
  568. };
  569. /**
  570. * Return the Color4 hash code as a number.
  571. */
  572. Color4.prototype.getHashCode = function () {
  573. var hash = this.r || 0;
  574. hash = (hash * 397) ^ (this.g || 0);
  575. hash = (hash * 397) ^ (this.b || 0);
  576. hash = (hash * 397) ^ (this.a || 0);
  577. return hash;
  578. };
  579. /**
  580. * Creates a new Color4 copied from the current one.
  581. */
  582. Color4.prototype.clone = function () {
  583. return new Color4(this.r, this.g, this.b, this.a);
  584. };
  585. /**
  586. * Copies the passed Color4 values into the current one.
  587. * Returns the updated Color4.
  588. */
  589. Color4.prototype.copyFrom = function (source) {
  590. this.r = source.r;
  591. this.g = source.g;
  592. this.b = source.b;
  593. this.a = source.a;
  594. return this;
  595. };
  596. /**
  597. * Copies the passed float values into the current one.
  598. * Returns the updated Color4.
  599. */
  600. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  601. this.r = r;
  602. this.g = g;
  603. this.b = b;
  604. this.a = a;
  605. return this;
  606. };
  607. /**
  608. * Copies the passed float values into the current one.
  609. * Returns the updated Color4.
  610. */
  611. Color4.prototype.set = function (r, g, b, a) {
  612. return this.copyFromFloats(r, g, b, a);
  613. };
  614. /**
  615. * Returns a string containing the hexadecimal Color4 code.
  616. */
  617. Color4.prototype.toHexString = function () {
  618. var intR = (this.r * 255) | 0;
  619. var intG = (this.g * 255) | 0;
  620. var intB = (this.b * 255) | 0;
  621. var intA = (this.a * 255) | 0;
  622. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  623. };
  624. /**
  625. * Returns a new Color4 converted to linear space.
  626. */
  627. Color4.prototype.toLinearSpace = function () {
  628. var convertedColor = new Color4();
  629. this.toLinearSpaceToRef(convertedColor);
  630. return convertedColor;
  631. };
  632. /**
  633. * Converts the Color4 values to linear space and stores the result in "convertedColor".
  634. * Returns the unmodified Color4.
  635. */
  636. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  637. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  638. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  639. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  640. convertedColor.a = this.a;
  641. return this;
  642. };
  643. /**
  644. * Returns a new Color4 converted to gamma space.
  645. */
  646. Color4.prototype.toGammaSpace = function () {
  647. var convertedColor = new Color4();
  648. this.toGammaSpaceToRef(convertedColor);
  649. return convertedColor;
  650. };
  651. /**
  652. * Converts the Color4 values to gamma space and stores the result in "convertedColor".
  653. * Returns the unmodified Color4.
  654. */
  655. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  656. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  657. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  658. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  659. convertedColor.a = this.a;
  660. return this;
  661. };
  662. // Statics
  663. /**
  664. * Creates a new Color4 from the valid hexadecimal value contained in the passed string.
  665. */
  666. Color4.FromHexString = function (hex) {
  667. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  668. //Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  669. return new Color4(0.0, 0.0, 0.0, 0.0);
  670. }
  671. var r = parseInt(hex.substring(1, 3), 16);
  672. var g = parseInt(hex.substring(3, 5), 16);
  673. var b = parseInt(hex.substring(5, 7), 16);
  674. var a = parseInt(hex.substring(7, 9), 16);
  675. return Color4.FromInts(r, g, b, a);
  676. };
  677. /**
  678. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  679. */
  680. Color4.Lerp = function (left, right, amount) {
  681. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  682. Color4.LerpToRef(left, right, amount, result);
  683. return result;
  684. };
  685. /**
  686. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  687. */
  688. Color4.LerpToRef = function (left, right, amount, result) {
  689. result.r = left.r + (right.r - left.r) * amount;
  690. result.g = left.g + (right.g - left.g) * amount;
  691. result.b = left.b + (right.b - left.b) * amount;
  692. result.a = left.a + (right.a - left.a) * amount;
  693. };
  694. /**
  695. * Creates a new Color4 from the starting index element of the passed array.
  696. */
  697. Color4.FromArray = function (array, offset) {
  698. if (offset === void 0) { offset = 0; }
  699. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  700. };
  701. /**
  702. * Creates a new Color4 from the passed integers ( < 256 ).
  703. */
  704. Color4.FromInts = function (r, g, b, a) {
  705. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  706. };
  707. Color4.CheckColors4 = function (colors, count) {
  708. // Check if color3 was used
  709. if (colors.length === count * 3) {
  710. var colors4 = [];
  711. for (var index = 0; index < colors.length; index += 3) {
  712. var newIndex = (index / 3) * 4;
  713. colors4[newIndex] = colors[index];
  714. colors4[newIndex + 1] = colors[index + 1];
  715. colors4[newIndex + 2] = colors[index + 2];
  716. colors4[newIndex + 3] = 1.0;
  717. }
  718. return colors4;
  719. }
  720. return colors;
  721. };
  722. return Color4;
  723. }());
  724. BABYLON.Color4 = Color4;
  725. var Vector2 = /** @class */ (function () {
  726. /**
  727. * Creates a new Vector2 from the passed x and y coordinates.
  728. */
  729. function Vector2(x, y) {
  730. this.x = x;
  731. this.y = y;
  732. }
  733. /**
  734. * Returns a string with the Vector2 coordinates.
  735. */
  736. Vector2.prototype.toString = function () {
  737. return "{X: " + this.x + " Y:" + this.y + "}";
  738. };
  739. /**
  740. * Returns the string "Vector2"
  741. */
  742. Vector2.prototype.getClassName = function () {
  743. return "Vector2";
  744. };
  745. /**
  746. * Returns the Vector2 hash code as a number.
  747. */
  748. Vector2.prototype.getHashCode = function () {
  749. var hash = this.x || 0;
  750. hash = (hash * 397) ^ (this.y || 0);
  751. return hash;
  752. };
  753. // Operators
  754. /**
  755. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  756. * Returns the Vector2.
  757. */
  758. Vector2.prototype.toArray = function (array, index) {
  759. if (index === void 0) { index = 0; }
  760. array[index] = this.x;
  761. array[index + 1] = this.y;
  762. return this;
  763. };
  764. /**
  765. * Returns a new array with 2 elements : the Vector2 coordinates.
  766. */
  767. Vector2.prototype.asArray = function () {
  768. var result = new Array();
  769. this.toArray(result, 0);
  770. return result;
  771. };
  772. /**
  773. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  774. * Returns the updated Vector2.
  775. */
  776. Vector2.prototype.copyFrom = function (source) {
  777. this.x = source.x;
  778. this.y = source.y;
  779. return this;
  780. };
  781. /**
  782. * Sets the Vector2 coordinates with the passed floats.
  783. * Returns the updated Vector2.
  784. */
  785. Vector2.prototype.copyFromFloats = function (x, y) {
  786. this.x = x;
  787. this.y = y;
  788. return this;
  789. };
  790. /**
  791. * Sets the Vector2 coordinates with the passed floats.
  792. * Returns the updated Vector2.
  793. */
  794. Vector2.prototype.set = function (x, y) {
  795. return this.copyFromFloats(x, y);
  796. };
  797. /**
  798. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  799. */
  800. Vector2.prototype.add = function (otherVector) {
  801. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  802. };
  803. /**
  804. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  805. * Returns the Vector2.
  806. */
  807. Vector2.prototype.addToRef = function (otherVector, result) {
  808. result.x = this.x + otherVector.x;
  809. result.y = this.y + otherVector.y;
  810. return this;
  811. };
  812. /**
  813. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  814. * Returns the updated Vector2.
  815. */
  816. Vector2.prototype.addInPlace = function (otherVector) {
  817. this.x += otherVector.x;
  818. this.y += otherVector.y;
  819. return this;
  820. };
  821. /**
  822. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  823. */
  824. Vector2.prototype.addVector3 = function (otherVector) {
  825. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  826. };
  827. /**
  828. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  829. */
  830. Vector2.prototype.subtract = function (otherVector) {
  831. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  832. };
  833. /**
  834. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  835. * Returns the Vector2.
  836. */
  837. Vector2.prototype.subtractToRef = function (otherVector, result) {
  838. result.x = this.x - otherVector.x;
  839. result.y = this.y - otherVector.y;
  840. return this;
  841. };
  842. /**
  843. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  844. * Returns the updated Vector2.
  845. */
  846. Vector2.prototype.subtractInPlace = function (otherVector) {
  847. this.x -= otherVector.x;
  848. this.y -= otherVector.y;
  849. return this;
  850. };
  851. /**
  852. * Multiplies in place the current Vector2 coordinates by the passed ones.
  853. * Returns the updated Vector2.
  854. */
  855. Vector2.prototype.multiplyInPlace = function (otherVector) {
  856. this.x *= otherVector.x;
  857. this.y *= otherVector.y;
  858. return this;
  859. };
  860. /**
  861. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  862. */
  863. Vector2.prototype.multiply = function (otherVector) {
  864. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  865. };
  866. /**
  867. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  868. * Returns the Vector2.
  869. */
  870. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  871. result.x = this.x * otherVector.x;
  872. result.y = this.y * otherVector.y;
  873. return this;
  874. };
  875. /**
  876. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  877. */
  878. Vector2.prototype.multiplyByFloats = function (x, y) {
  879. return new Vector2(this.x * x, this.y * y);
  880. };
  881. /**
  882. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  883. */
  884. Vector2.prototype.divide = function (otherVector) {
  885. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  886. };
  887. /**
  888. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  889. * Returns the Vector2.
  890. */
  891. Vector2.prototype.divideToRef = function (otherVector, result) {
  892. result.x = this.x / otherVector.x;
  893. result.y = this.y / otherVector.y;
  894. return this;
  895. };
  896. /**
  897. * Returns a new Vector2 with current Vector2 negated coordinates.
  898. */
  899. Vector2.prototype.negate = function () {
  900. return new Vector2(-this.x, -this.y);
  901. };
  902. /**
  903. * Multiply the Vector2 coordinates by scale.
  904. * Returns the updated Vector2.
  905. */
  906. Vector2.prototype.scaleInPlace = function (scale) {
  907. this.x *= scale;
  908. this.y *= scale;
  909. return this;
  910. };
  911. /**
  912. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  913. */
  914. Vector2.prototype.scale = function (scale) {
  915. return new Vector2(this.x * scale, this.y * scale);
  916. };
  917. /**
  918. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  919. */
  920. Vector2.prototype.equals = function (otherVector) {
  921. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  922. };
  923. /**
  924. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  925. */
  926. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  927. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  928. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  929. };
  930. // Properties
  931. /**
  932. * Returns the vector length (float).
  933. */
  934. Vector2.prototype.length = function () {
  935. return Math.sqrt(this.x * this.x + this.y * this.y);
  936. };
  937. /**
  938. * Returns the vector squared length (float);
  939. */
  940. Vector2.prototype.lengthSquared = function () {
  941. return (this.x * this.x + this.y * this.y);
  942. };
  943. // Methods
  944. /**
  945. * Normalize the vector.
  946. * Returns the updated Vector2.
  947. */
  948. Vector2.prototype.normalize = function () {
  949. var len = this.length();
  950. if (len === 0)
  951. return this;
  952. var num = 1.0 / len;
  953. this.x *= num;
  954. this.y *= num;
  955. return this;
  956. };
  957. /**
  958. * Returns a new Vector2 copied from the Vector2.
  959. */
  960. Vector2.prototype.clone = function () {
  961. return new Vector2(this.x, this.y);
  962. };
  963. // Statics
  964. /**
  965. * Returns a new Vector2(0, 0)
  966. */
  967. Vector2.Zero = function () {
  968. return new Vector2(0, 0);
  969. };
  970. /**
  971. * Returns a new Vector2(1, 1)
  972. */
  973. Vector2.One = function () {
  974. return new Vector2(1, 1);
  975. };
  976. /**
  977. * Returns a new Vector2 set from the passed index element of the passed array.
  978. */
  979. Vector2.FromArray = function (array, offset) {
  980. if (offset === void 0) { offset = 0; }
  981. return new Vector2(array[offset], array[offset + 1]);
  982. };
  983. /**
  984. * Sets "result" from the passed index element of the passed array.
  985. */
  986. Vector2.FromArrayToRef = function (array, offset, result) {
  987. result.x = array[offset];
  988. result.y = array[offset + 1];
  989. };
  990. /**
  991. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  992. */
  993. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  994. var squared = amount * amount;
  995. var cubed = amount * squared;
  996. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  997. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  998. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  999. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  1000. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  1001. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  1002. return new Vector2(x, y);
  1003. };
  1004. /**
  1005. * 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".
  1006. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  1007. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  1008. */
  1009. Vector2.Clamp = function (value, min, max) {
  1010. var x = value.x;
  1011. x = (x > max.x) ? max.x : x;
  1012. x = (x < min.x) ? min.x : x;
  1013. var y = value.y;
  1014. y = (y > max.y) ? max.y : y;
  1015. y = (y < min.y) ? min.y : y;
  1016. return new Vector2(x, y);
  1017. };
  1018. /**
  1019. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  1020. */
  1021. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  1022. var squared = amount * amount;
  1023. var cubed = amount * squared;
  1024. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  1025. var part2 = (-2.0 * cubed) + (3.0 * squared);
  1026. var part3 = (cubed - (2.0 * squared)) + amount;
  1027. var part4 = cubed - squared;
  1028. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  1029. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  1030. return new Vector2(x, y);
  1031. };
  1032. /**
  1033. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  1034. */
  1035. Vector2.Lerp = function (start, end, amount) {
  1036. var x = start.x + ((end.x - start.x) * amount);
  1037. var y = start.y + ((end.y - start.y) * amount);
  1038. return new Vector2(x, y);
  1039. };
  1040. /**
  1041. * Returns the dot product (float) of the vector "left" and the vector "right".
  1042. */
  1043. Vector2.Dot = function (left, right) {
  1044. return left.x * right.x + left.y * right.y;
  1045. };
  1046. /**
  1047. * Returns a new Vector2 equal to the normalized passed vector.
  1048. */
  1049. Vector2.Normalize = function (vector) {
  1050. var newVector = vector.clone();
  1051. newVector.normalize();
  1052. return newVector;
  1053. };
  1054. /**
  1055. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  1056. */
  1057. Vector2.Minimize = function (left, right) {
  1058. var x = (left.x < right.x) ? left.x : right.x;
  1059. var y = (left.y < right.y) ? left.y : right.y;
  1060. return new Vector2(x, y);
  1061. };
  1062. /**
  1063. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  1064. */
  1065. Vector2.Maximize = function (left, right) {
  1066. var x = (left.x > right.x) ? left.x : right.x;
  1067. var y = (left.y > right.y) ? left.y : right.y;
  1068. return new Vector2(x, y);
  1069. };
  1070. /**
  1071. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  1072. */
  1073. Vector2.Transform = function (vector, transformation) {
  1074. var r = Vector2.Zero();
  1075. Vector2.TransformToRef(vector, transformation, r);
  1076. return r;
  1077. };
  1078. /**
  1079. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  1080. */
  1081. Vector2.TransformToRef = function (vector, transformation, result) {
  1082. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  1083. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  1084. result.x = x;
  1085. result.y = y;
  1086. };
  1087. /**
  1088. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  1089. */
  1090. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  1091. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  1092. var sign = a < 0 ? -1 : 1;
  1093. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  1094. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  1095. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  1096. };
  1097. /**
  1098. * Returns the distance (float) between the vectors "value1" and "value2".
  1099. */
  1100. Vector2.Distance = function (value1, value2) {
  1101. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  1102. };
  1103. /**
  1104. * Returns the squared distance (float) between the vectors "value1" and "value2".
  1105. */
  1106. Vector2.DistanceSquared = function (value1, value2) {
  1107. var x = value1.x - value2.x;
  1108. var y = value1.y - value2.y;
  1109. return (x * x) + (y * y);
  1110. };
  1111. /**
  1112. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  1113. */
  1114. Vector2.Center = function (value1, value2) {
  1115. var center = value1.add(value2);
  1116. center.scaleInPlace(0.5);
  1117. return center;
  1118. };
  1119. /**
  1120. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  1121. */
  1122. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  1123. var l2 = Vector2.DistanceSquared(segA, segB);
  1124. if (l2 === 0.0) {
  1125. return Vector2.Distance(p, segA);
  1126. }
  1127. var v = segB.subtract(segA);
  1128. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  1129. var proj = segA.add(v.multiplyByFloats(t, t));
  1130. return Vector2.Distance(p, proj);
  1131. };
  1132. return Vector2;
  1133. }());
  1134. BABYLON.Vector2 = Vector2;
  1135. var Vector3 = /** @class */ (function () {
  1136. /**
  1137. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  1138. * A Vector3 is the main object used in 3D geometry.
  1139. * It can represent etiher the coordinates of a point the space, either a direction.
  1140. */
  1141. function Vector3(x, y, z) {
  1142. this.x = x;
  1143. this.y = y;
  1144. this.z = z;
  1145. }
  1146. /**
  1147. * Returns a string with the Vector3 coordinates.
  1148. */
  1149. Vector3.prototype.toString = function () {
  1150. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  1151. };
  1152. /**
  1153. * Returns the string "Vector3"
  1154. */
  1155. Vector3.prototype.getClassName = function () {
  1156. return "Vector3";
  1157. };
  1158. /**
  1159. * Returns the Vector hash code.
  1160. */
  1161. Vector3.prototype.getHashCode = function () {
  1162. var hash = this.x || 0;
  1163. hash = (hash * 397) ^ (this.y || 0);
  1164. hash = (hash * 397) ^ (this.z || 0);
  1165. return hash;
  1166. };
  1167. // Operators
  1168. /**
  1169. * Returns a new array with three elements : the coordinates the Vector3.
  1170. */
  1171. Vector3.prototype.asArray = function () {
  1172. var result = [];
  1173. this.toArray(result, 0);
  1174. return result;
  1175. };
  1176. /**
  1177. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3.
  1178. * Returns the Vector3.
  1179. */
  1180. Vector3.prototype.toArray = function (array, index) {
  1181. if (index === void 0) { index = 0; }
  1182. array[index] = this.x;
  1183. array[index + 1] = this.y;
  1184. array[index + 2] = this.z;
  1185. return this;
  1186. };
  1187. /**
  1188. * Returns a new Quaternion object, computed from the Vector3 coordinates.
  1189. */
  1190. Vector3.prototype.toQuaternion = function () {
  1191. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  1192. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  1193. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  1194. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  1195. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  1196. var cosy = Math.cos(this.y * 0.5);
  1197. var siny = Math.sin(this.y * 0.5);
  1198. result.x = coszMinusx * siny;
  1199. result.y = -sinzMinusx * siny;
  1200. result.z = sinxPlusz * cosy;
  1201. result.w = cosxPlusz * cosy;
  1202. return result;
  1203. };
  1204. /**
  1205. * Adds the passed vector to the current Vector3.
  1206. * Returns the updated Vector3.
  1207. */
  1208. Vector3.prototype.addInPlace = function (otherVector) {
  1209. this.x += otherVector.x;
  1210. this.y += otherVector.y;
  1211. this.z += otherVector.z;
  1212. return this;
  1213. };
  1214. /**
  1215. * Returns a new Vector3, result of the addition the current Vector3 and the passed vector.
  1216. */
  1217. Vector3.prototype.add = function (otherVector) {
  1218. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  1219. };
  1220. /**
  1221. * Adds the current Vector3 to the passed one and stores the result in the vector "result".
  1222. * Returns the current Vector3.
  1223. */
  1224. Vector3.prototype.addToRef = function (otherVector, result) {
  1225. result.x = this.x + otherVector.x;
  1226. result.y = this.y + otherVector.y;
  1227. result.z = this.z + otherVector.z;
  1228. return this;
  1229. };
  1230. /**
  1231. * Subtract the passed vector from the current Vector3.
  1232. * Returns the updated Vector3.
  1233. */
  1234. Vector3.prototype.subtractInPlace = function (otherVector) {
  1235. this.x -= otherVector.x;
  1236. this.y -= otherVector.y;
  1237. this.z -= otherVector.z;
  1238. return this;
  1239. };
  1240. /**
  1241. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3.
  1242. */
  1243. Vector3.prototype.subtract = function (otherVector) {
  1244. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  1245. };
  1246. /**
  1247. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  1248. * Returns the current Vector3.
  1249. */
  1250. Vector3.prototype.subtractToRef = function (otherVector, result) {
  1251. result.x = this.x - otherVector.x;
  1252. result.y = this.y - otherVector.y;
  1253. result.z = this.z - otherVector.z;
  1254. return this;
  1255. };
  1256. /**
  1257. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates.
  1258. */
  1259. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  1260. return new Vector3(this.x - x, this.y - y, this.z - z);
  1261. };
  1262. /**
  1263. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result.
  1264. * Returns the current Vector3.
  1265. */
  1266. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  1267. result.x = this.x - x;
  1268. result.y = this.y - y;
  1269. result.z = this.z - z;
  1270. return this;
  1271. };
  1272. /**
  1273. * Returns a new Vector3 set with the current Vector3 negated coordinates.
  1274. */
  1275. Vector3.prototype.negate = function () {
  1276. return new Vector3(-this.x, -this.y, -this.z);
  1277. };
  1278. /**
  1279. * Multiplies the Vector3 coordinates by the float "scale".
  1280. * Returns the updated Vector3.
  1281. */
  1282. Vector3.prototype.scaleInPlace = function (scale) {
  1283. this.x *= scale;
  1284. this.y *= scale;
  1285. this.z *= scale;
  1286. return this;
  1287. };
  1288. /**
  1289. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale".
  1290. */
  1291. Vector3.prototype.scale = function (scale) {
  1292. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  1293. };
  1294. /**
  1295. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates.
  1296. * Returns the current Vector3.
  1297. */
  1298. Vector3.prototype.scaleToRef = function (scale, result) {
  1299. result.x = this.x * scale;
  1300. result.y = this.y * scale;
  1301. result.z = this.z * scale;
  1302. return this;
  1303. };
  1304. /**
  1305. * Boolean : True if the current Vector3 and the passed vector coordinates are strictly equal.
  1306. */
  1307. Vector3.prototype.equals = function (otherVector) {
  1308. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  1309. };
  1310. /**
  1311. * Boolean : True if the current Vector3 and the passed vector coordinates are distant less than epsilon.
  1312. */
  1313. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1314. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1315. 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);
  1316. };
  1317. /**
  1318. * Boolean : True if the current Vector3 coordinate equal the passed floats.
  1319. */
  1320. Vector3.prototype.equalsToFloats = function (x, y, z) {
  1321. return this.x === x && this.y === y && this.z === z;
  1322. };
  1323. /**
  1324. * Muliplies the current Vector3 coordinates by the passed ones.
  1325. * Returns the updated Vector3.
  1326. */
  1327. Vector3.prototype.multiplyInPlace = function (otherVector) {
  1328. this.x *= otherVector.x;
  1329. this.y *= otherVector.y;
  1330. this.z *= otherVector.z;
  1331. return this;
  1332. };
  1333. /**
  1334. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector.
  1335. */
  1336. Vector3.prototype.multiply = function (otherVector) {
  1337. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  1338. };
  1339. /**
  1340. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result".
  1341. * Returns the current Vector3.
  1342. */
  1343. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  1344. result.x = this.x * otherVector.x;
  1345. result.y = this.y * otherVector.y;
  1346. result.z = this.z * otherVector.z;
  1347. return this;
  1348. };
  1349. /**
  1350. * Returns a new Vector3 set witth the result of the mulliplication of the current Vector3 coordinates by the passed floats.
  1351. */
  1352. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  1353. return new Vector3(this.x * x, this.y * y, this.z * z);
  1354. };
  1355. /**
  1356. * Returns a new Vector3 set witth the result of the division of the current Vector3 coordinates by the passed ones.
  1357. */
  1358. Vector3.prototype.divide = function (otherVector) {
  1359. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  1360. };
  1361. /**
  1362. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result".
  1363. * Returns the current Vector3.
  1364. */
  1365. Vector3.prototype.divideToRef = function (otherVector, result) {
  1366. result.x = this.x / otherVector.x;
  1367. result.y = this.y / otherVector.y;
  1368. result.z = this.z / otherVector.z;
  1369. return this;
  1370. };
  1371. /**
  1372. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones.
  1373. * Returns the updated Vector3.
  1374. */
  1375. Vector3.prototype.MinimizeInPlace = function (other) {
  1376. if (other.x < this.x)
  1377. this.x = other.x;
  1378. if (other.y < this.y)
  1379. this.y = other.y;
  1380. if (other.z < this.z)
  1381. this.z = other.z;
  1382. return this;
  1383. };
  1384. /**
  1385. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  1386. * Returns the updated Vector3.
  1387. */
  1388. Vector3.prototype.MaximizeInPlace = function (other) {
  1389. if (other.x > this.x)
  1390. this.x = other.x;
  1391. if (other.y > this.y)
  1392. this.y = other.y;
  1393. if (other.z > this.z)
  1394. this.z = other.z;
  1395. return this;
  1396. };
  1397. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  1398. /**
  1399. * Return true is the vector is non uniform meaning x, y or z are not all the same.
  1400. */
  1401. get: function () {
  1402. var absX = Math.abs(this.x);
  1403. var absY = Math.abs(this.y);
  1404. if (absX !== absY) {
  1405. return true;
  1406. }
  1407. var absZ = Math.abs(this.z);
  1408. if (absX !== absZ) {
  1409. return true;
  1410. }
  1411. if (absY !== absZ) {
  1412. return true;
  1413. }
  1414. return false;
  1415. },
  1416. enumerable: true,
  1417. configurable: true
  1418. });
  1419. // Properties
  1420. /**
  1421. * Returns the length of the Vector3 (float).
  1422. */
  1423. Vector3.prototype.length = function () {
  1424. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  1425. };
  1426. /**
  1427. * Returns the squared length of the Vector3 (float).
  1428. */
  1429. Vector3.prototype.lengthSquared = function () {
  1430. return (this.x * this.x + this.y * this.y + this.z * this.z);
  1431. };
  1432. /**
  1433. * Normalize the current Vector3.
  1434. * Returns the updated Vector3.
  1435. * /!\ In place operation.
  1436. */
  1437. Vector3.prototype.normalize = function () {
  1438. var len = this.length();
  1439. if (len === 0 || len === 1.0)
  1440. return this;
  1441. var num = 1.0 / len;
  1442. this.x *= num;
  1443. this.y *= num;
  1444. this.z *= num;
  1445. return this;
  1446. };
  1447. /**
  1448. * Normalize the current Vector3 to a new vector.
  1449. * @returns the new Vector3.
  1450. */
  1451. Vector3.prototype.normalizeToNew = function () {
  1452. var normalized = new Vector3(0, 0, 0);
  1453. this.normalizeToRef(normalized);
  1454. return normalized;
  1455. };
  1456. /**
  1457. * Normalize the current Vector3 to the reference.
  1458. * @param the reference to update.
  1459. * @returns the updated Vector3.
  1460. */
  1461. Vector3.prototype.normalizeToRef = function (reference) {
  1462. var len = this.length();
  1463. if (len === 0 || len === 1.0) {
  1464. reference.set(this.x, this.y, this.z);
  1465. return reference;
  1466. }
  1467. var scale = 1.0 / len;
  1468. this.scaleToRef(scale, reference);
  1469. return reference;
  1470. };
  1471. /**
  1472. * Returns a new Vector3 copied from the current Vector3.
  1473. */
  1474. Vector3.prototype.clone = function () {
  1475. return new Vector3(this.x, this.y, this.z);
  1476. };
  1477. /**
  1478. * Copies the passed vector coordinates to the current Vector3 ones.
  1479. * Returns the updated Vector3.
  1480. */
  1481. Vector3.prototype.copyFrom = function (source) {
  1482. this.x = source.x;
  1483. this.y = source.y;
  1484. this.z = source.z;
  1485. return this;
  1486. };
  1487. /**
  1488. * Copies the passed floats to the current Vector3 coordinates.
  1489. * Returns the updated Vector3.
  1490. */
  1491. Vector3.prototype.copyFromFloats = function (x, y, z) {
  1492. this.x = x;
  1493. this.y = y;
  1494. this.z = z;
  1495. return this;
  1496. };
  1497. /**
  1498. * Copies the passed floats to the current Vector3 coordinates.
  1499. * Returns the updated Vector3.
  1500. */
  1501. Vector3.prototype.set = function (x, y, z) {
  1502. return this.copyFromFloats(x, y, z);
  1503. };
  1504. // Statics
  1505. /**
  1506. *
  1507. */
  1508. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  1509. var d0 = Vector3.Dot(vector0, axis) - size;
  1510. var d1 = Vector3.Dot(vector1, axis) - size;
  1511. var s = d0 / (d0 - d1);
  1512. return s;
  1513. };
  1514. /**
  1515. * Returns a new Vector3 set from the index "offset" of the passed array.
  1516. */
  1517. Vector3.FromArray = function (array, offset) {
  1518. if (!offset) {
  1519. offset = 0;
  1520. }
  1521. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  1522. };
  1523. /**
  1524. * Returns a new Vector3 set from the index "offset" of the passed Float32Array.
  1525. * This function is deprecated. Use FromArray instead.
  1526. */
  1527. Vector3.FromFloatArray = function (array, offset) {
  1528. return Vector3.FromArray(array, offset);
  1529. };
  1530. /**
  1531. * Sets the passed vector "result" with the element values from the index "offset" of the passed array.
  1532. */
  1533. Vector3.FromArrayToRef = function (array, offset, result) {
  1534. result.x = array[offset];
  1535. result.y = array[offset + 1];
  1536. result.z = array[offset + 2];
  1537. };
  1538. /**
  1539. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array.
  1540. * This function is deprecated. Use FromArrayToRef instead.
  1541. */
  1542. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  1543. return Vector3.FromArrayToRef(array, offset, result);
  1544. };
  1545. /**
  1546. * Sets the passed vector "result" with the passed floats.
  1547. */
  1548. Vector3.FromFloatsToRef = function (x, y, z, result) {
  1549. result.x = x;
  1550. result.y = y;
  1551. result.z = z;
  1552. };
  1553. /**
  1554. * Returns a new Vector3 set to (0.0, 0.0, 0.0).
  1555. */
  1556. Vector3.Zero = function () {
  1557. return new Vector3(0.0, 0.0, 0.0);
  1558. };
  1559. /**
  1560. * Returns a new Vector3 set to (1.0, 1.0, 1.0).
  1561. */
  1562. Vector3.One = function () {
  1563. return new Vector3(1.0, 1.0, 1.0);
  1564. };
  1565. /**
  1566. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  1567. */
  1568. Vector3.Up = function () {
  1569. return new Vector3(0.0, 1.0, 0.0);
  1570. };
  1571. /**
  1572. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  1573. */
  1574. Vector3.Forward = function () {
  1575. return new Vector3(0.0, 0.0, 1.0);
  1576. };
  1577. /**
  1578. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  1579. */
  1580. Vector3.Right = function () {
  1581. return new Vector3(1.0, 0.0, 0.0);
  1582. };
  1583. /**
  1584. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  1585. */
  1586. Vector3.Left = function () {
  1587. return new Vector3(-1.0, 0.0, 0.0);
  1588. };
  1589. /**
  1590. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  1591. * This method computes tranformed coordinates only, not transformed direction vectors.
  1592. */
  1593. Vector3.TransformCoordinates = function (vector, transformation) {
  1594. var result = Vector3.Zero();
  1595. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  1596. return result;
  1597. };
  1598. /**
  1599. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector.
  1600. * This method computes tranformed coordinates only, not transformed direction vectors.
  1601. */
  1602. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  1603. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  1604. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  1605. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  1606. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  1607. result.x = x / w;
  1608. result.y = y / w;
  1609. result.z = z / w;
  1610. };
  1611. /**
  1612. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z).
  1613. * This method computes tranformed coordinates only, not transformed direction vectors.
  1614. */
  1615. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  1616. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  1617. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  1618. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  1619. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  1620. result.x = rx / rw;
  1621. result.y = ry / rw;
  1622. result.z = rz / rw;
  1623. };
  1624. /**
  1625. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector.
  1626. * This methods computes transformed normalized direction vectors only.
  1627. */
  1628. Vector3.TransformNormal = function (vector, transformation) {
  1629. var result = Vector3.Zero();
  1630. Vector3.TransformNormalToRef(vector, transformation, result);
  1631. return result;
  1632. };
  1633. /**
  1634. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  1635. * This methods computes transformed normalized direction vectors only.
  1636. */
  1637. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  1638. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  1639. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  1640. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  1641. result.x = x;
  1642. result.y = y;
  1643. result.z = z;
  1644. };
  1645. /**
  1646. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z).
  1647. * This methods computes transformed normalized direction vectors only.
  1648. */
  1649. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  1650. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  1651. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  1652. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  1653. };
  1654. /**
  1655. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4".
  1656. */
  1657. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  1658. var squared = amount * amount;
  1659. var cubed = amount * squared;
  1660. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  1661. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  1662. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  1663. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  1664. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  1665. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  1666. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  1667. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  1668. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  1669. return new Vector3(x, y, z);
  1670. };
  1671. /**
  1672. * 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".
  1673. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one.
  1674. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one.
  1675. */
  1676. Vector3.Clamp = function (value, min, max) {
  1677. var x = value.x;
  1678. x = (x > max.x) ? max.x : x;
  1679. x = (x < min.x) ? min.x : x;
  1680. var y = value.y;
  1681. y = (y > max.y) ? max.y : y;
  1682. y = (y < min.y) ? min.y : y;
  1683. var z = value.z;
  1684. z = (z > max.z) ? max.z : z;
  1685. z = (z < min.z) ? min.z : z;
  1686. return new Vector3(x, y, z);
  1687. };
  1688. /**
  1689. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  1690. */
  1691. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  1692. var squared = amount * amount;
  1693. var cubed = amount * squared;
  1694. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  1695. var part2 = (-2.0 * cubed) + (3.0 * squared);
  1696. var part3 = (cubed - (2.0 * squared)) + amount;
  1697. var part4 = cubed - squared;
  1698. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  1699. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  1700. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  1701. return new Vector3(x, y, z);
  1702. };
  1703. /**
  1704. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end".
  1705. */
  1706. Vector3.Lerp = function (start, end, amount) {
  1707. var result = new Vector3(0, 0, 0);
  1708. Vector3.LerpToRef(start, end, amount, result);
  1709. return result;
  1710. };
  1711. /**
  1712. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end".
  1713. */
  1714. Vector3.LerpToRef = function (start, end, amount, result) {
  1715. result.x = start.x + ((end.x - start.x) * amount);
  1716. result.y = start.y + ((end.y - start.y) * amount);
  1717. result.z = start.z + ((end.z - start.z) * amount);
  1718. };
  1719. /**
  1720. * Returns the dot product (float) between the vectors "left" and "right".
  1721. */
  1722. Vector3.Dot = function (left, right) {
  1723. return (left.x * right.x + left.y * right.y + left.z * right.z);
  1724. };
  1725. /**
  1726. * Returns a new Vector3 as the cross product of the vectors "left" and "right".
  1727. * The cross product is then orthogonal to both "left" and "right".
  1728. */
  1729. Vector3.Cross = function (left, right) {
  1730. var result = Vector3.Zero();
  1731. Vector3.CrossToRef(left, right, result);
  1732. return result;
  1733. };
  1734. /**
  1735. * Sets the passed vector "result" with the cross product of "left" and "right".
  1736. * The cross product is then orthogonal to both "left" and "right".
  1737. */
  1738. Vector3.CrossToRef = function (left, right, result) {
  1739. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  1740. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  1741. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  1742. result.copyFrom(MathTmp.Vector3[0]);
  1743. };
  1744. /**
  1745. * Returns a new Vector3 as the normalization of the passed vector.
  1746. */
  1747. Vector3.Normalize = function (vector) {
  1748. var result = Vector3.Zero();
  1749. Vector3.NormalizeToRef(vector, result);
  1750. return result;
  1751. };
  1752. /**
  1753. * Sets the passed vector "result" with the normalization of the passed first vector.
  1754. */
  1755. Vector3.NormalizeToRef = function (vector, result) {
  1756. result.copyFrom(vector);
  1757. result.normalize();
  1758. };
  1759. Vector3.Project = function (vector, world, transform, viewport) {
  1760. var cw = viewport.width;
  1761. var ch = viewport.height;
  1762. var cx = viewport.x;
  1763. var cy = viewport.y;
  1764. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  1765. 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);
  1766. var matrix = MathTmp.Matrix[0];
  1767. world.multiplyToRef(transform, matrix);
  1768. matrix.multiplyToRef(viewportMatrix, matrix);
  1769. return Vector3.TransformCoordinates(vector, matrix);
  1770. };
  1771. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  1772. var matrix = MathTmp.Matrix[0];
  1773. world.multiplyToRef(transform, matrix);
  1774. matrix.invert();
  1775. source.x = source.x / viewportWidth * 2 - 1;
  1776. source.y = -(source.y / viewportHeight * 2 - 1);
  1777. var vector = Vector3.TransformCoordinates(source, matrix);
  1778. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  1779. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  1780. vector = vector.scale(1.0 / num);
  1781. }
  1782. return vector;
  1783. };
  1784. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  1785. var result = Vector3.Zero();
  1786. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  1787. return result;
  1788. };
  1789. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  1790. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  1791. };
  1792. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  1793. var matrix = MathTmp.Matrix[0];
  1794. world.multiplyToRef(view, matrix);
  1795. matrix.multiplyToRef(projection, matrix);
  1796. matrix.invert();
  1797. var screenSource = MathTmp.Vector3[0];
  1798. screenSource.x = sourceX / viewportWidth * 2 - 1;
  1799. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  1800. screenSource.z = 2 * sourceZ - 1.0;
  1801. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  1802. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  1803. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  1804. result.scaleInPlace(1.0 / num);
  1805. }
  1806. };
  1807. Vector3.Minimize = function (left, right) {
  1808. var min = left.clone();
  1809. min.MinimizeInPlace(right);
  1810. return min;
  1811. };
  1812. Vector3.Maximize = function (left, right) {
  1813. var max = left.clone();
  1814. max.MaximizeInPlace(right);
  1815. return max;
  1816. };
  1817. /**
  1818. * Returns the distance (float) between the vectors "value1" and "value2".
  1819. */
  1820. Vector3.Distance = function (value1, value2) {
  1821. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  1822. };
  1823. /**
  1824. * Returns the squared distance (float) between the vectors "value1" and "value2".
  1825. */
  1826. Vector3.DistanceSquared = function (value1, value2) {
  1827. var x = value1.x - value2.x;
  1828. var y = value1.y - value2.y;
  1829. var z = value1.z - value2.z;
  1830. return (x * x) + (y * y) + (z * z);
  1831. };
  1832. /**
  1833. * Returns a new Vector3 located at the center between "value1" and "value2".
  1834. */
  1835. Vector3.Center = function (value1, value2) {
  1836. var center = value1.add(value2);
  1837. center.scaleInPlace(0.5);
  1838. return center;
  1839. };
  1840. /**
  1841. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  1842. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  1843. * to something in order to rotate it from its local system to the given target system.
  1844. * Note : axis1, axis2 and axis3 are normalized during this operation.
  1845. * Returns a new Vector3.
  1846. */
  1847. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  1848. var rotation = Vector3.Zero();
  1849. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  1850. return rotation;
  1851. };
  1852. /**
  1853. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3.
  1854. */
  1855. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  1856. var quat = MathTmp.Quaternion[0];
  1857. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  1858. quat.toEulerAnglesToRef(ref);
  1859. };
  1860. return Vector3;
  1861. }());
  1862. BABYLON.Vector3 = Vector3;
  1863. //Vector4 class created for EulerAngle class conversion to Quaternion
  1864. var Vector4 = /** @class */ (function () {
  1865. /**
  1866. * Creates a Vector4 object from the passed floats.
  1867. */
  1868. function Vector4(x, y, z, w) {
  1869. this.x = x;
  1870. this.y = y;
  1871. this.z = z;
  1872. this.w = w;
  1873. }
  1874. /**
  1875. * Returns the string with the Vector4 coordinates.
  1876. */
  1877. Vector4.prototype.toString = function () {
  1878. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1879. };
  1880. /**
  1881. * Returns the string "Vector4".
  1882. */
  1883. Vector4.prototype.getClassName = function () {
  1884. return "Vector4";
  1885. };
  1886. /**
  1887. * Returns the Vector4 hash code.
  1888. */
  1889. Vector4.prototype.getHashCode = function () {
  1890. var hash = this.x || 0;
  1891. hash = (hash * 397) ^ (this.y || 0);
  1892. hash = (hash * 397) ^ (this.z || 0);
  1893. hash = (hash * 397) ^ (this.w || 0);
  1894. return hash;
  1895. };
  1896. // Operators
  1897. /**
  1898. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  1899. */
  1900. Vector4.prototype.asArray = function () {
  1901. var result = new Array();
  1902. this.toArray(result, 0);
  1903. return result;
  1904. };
  1905. /**
  1906. * Populates the passed array from the passed index with the Vector4 coordinates.
  1907. * Returns the Vector4.
  1908. */
  1909. Vector4.prototype.toArray = function (array, index) {
  1910. if (index === undefined) {
  1911. index = 0;
  1912. }
  1913. array[index] = this.x;
  1914. array[index + 1] = this.y;
  1915. array[index + 2] = this.z;
  1916. array[index + 3] = this.w;
  1917. return this;
  1918. };
  1919. /**
  1920. * Adds the passed vector to the current Vector4.
  1921. * Returns the updated Vector4.
  1922. */
  1923. Vector4.prototype.addInPlace = function (otherVector) {
  1924. this.x += otherVector.x;
  1925. this.y += otherVector.y;
  1926. this.z += otherVector.z;
  1927. this.w += otherVector.w;
  1928. return this;
  1929. };
  1930. /**
  1931. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  1932. */
  1933. Vector4.prototype.add = function (otherVector) {
  1934. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  1935. };
  1936. /**
  1937. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  1938. * Returns the current Vector4.
  1939. */
  1940. Vector4.prototype.addToRef = function (otherVector, result) {
  1941. result.x = this.x + otherVector.x;
  1942. result.y = this.y + otherVector.y;
  1943. result.z = this.z + otherVector.z;
  1944. result.w = this.w + otherVector.w;
  1945. return this;
  1946. };
  1947. /**
  1948. * Subtract in place the passed vector from the current Vector4.
  1949. * Returns the updated Vector4.
  1950. */
  1951. Vector4.prototype.subtractInPlace = function (otherVector) {
  1952. this.x -= otherVector.x;
  1953. this.y -= otherVector.y;
  1954. this.z -= otherVector.z;
  1955. this.w -= otherVector.w;
  1956. return this;
  1957. };
  1958. /**
  1959. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  1960. */
  1961. Vector4.prototype.subtract = function (otherVector) {
  1962. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  1963. };
  1964. /**
  1965. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  1966. * Returns the current Vector4.
  1967. */
  1968. Vector4.prototype.subtractToRef = function (otherVector, result) {
  1969. result.x = this.x - otherVector.x;
  1970. result.y = this.y - otherVector.y;
  1971. result.z = this.z - otherVector.z;
  1972. result.w = this.w - otherVector.w;
  1973. return this;
  1974. };
  1975. /**
  1976. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  1977. */
  1978. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  1979. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  1980. };
  1981. /**
  1982. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  1983. * Returns the current Vector4.
  1984. */
  1985. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  1986. result.x = this.x - x;
  1987. result.y = this.y - y;
  1988. result.z = this.z - z;
  1989. result.w = this.w - w;
  1990. return this;
  1991. };
  1992. /**
  1993. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  1994. */
  1995. Vector4.prototype.negate = function () {
  1996. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  1997. };
  1998. /**
  1999. * Multiplies the current Vector4 coordinates by scale (float).
  2000. * Returns the updated Vector4.
  2001. */
  2002. Vector4.prototype.scaleInPlace = function (scale) {
  2003. this.x *= scale;
  2004. this.y *= scale;
  2005. this.z *= scale;
  2006. this.w *= scale;
  2007. return this;
  2008. };
  2009. /**
  2010. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  2011. */
  2012. Vector4.prototype.scale = function (scale) {
  2013. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  2014. };
  2015. /**
  2016. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  2017. * Returns the current Vector4.
  2018. */
  2019. Vector4.prototype.scaleToRef = function (scale, result) {
  2020. result.x = this.x * scale;
  2021. result.y = this.y * scale;
  2022. result.z = this.z * scale;
  2023. result.w = this.w * scale;
  2024. return this;
  2025. };
  2026. /**
  2027. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  2028. */
  2029. Vector4.prototype.equals = function (otherVector) {
  2030. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  2031. };
  2032. /**
  2033. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  2034. */
  2035. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2036. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2037. return otherVector
  2038. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  2039. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  2040. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  2041. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  2042. };
  2043. /**
  2044. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  2045. */
  2046. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  2047. return this.x === x && this.y === y && this.z === z && this.w === w;
  2048. };
  2049. /**
  2050. * Multiplies in place the current Vector4 by the passed one.
  2051. * Returns the updated Vector4.
  2052. */
  2053. Vector4.prototype.multiplyInPlace = function (otherVector) {
  2054. this.x *= otherVector.x;
  2055. this.y *= otherVector.y;
  2056. this.z *= otherVector.z;
  2057. this.w *= otherVector.w;
  2058. return this;
  2059. };
  2060. /**
  2061. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  2062. */
  2063. Vector4.prototype.multiply = function (otherVector) {
  2064. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  2065. };
  2066. /**
  2067. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  2068. * Returns the current Vector4.
  2069. */
  2070. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  2071. result.x = this.x * otherVector.x;
  2072. result.y = this.y * otherVector.y;
  2073. result.z = this.z * otherVector.z;
  2074. result.w = this.w * otherVector.w;
  2075. return this;
  2076. };
  2077. /**
  2078. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  2079. */
  2080. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  2081. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  2082. };
  2083. /**
  2084. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  2085. */
  2086. Vector4.prototype.divide = function (otherVector) {
  2087. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  2088. };
  2089. /**
  2090. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  2091. * Returns the current Vector4.
  2092. */
  2093. Vector4.prototype.divideToRef = function (otherVector, result) {
  2094. result.x = this.x / otherVector.x;
  2095. result.y = this.y / otherVector.y;
  2096. result.z = this.z / otherVector.z;
  2097. result.w = this.w / otherVector.w;
  2098. return this;
  2099. };
  2100. /**
  2101. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones.
  2102. */
  2103. Vector4.prototype.MinimizeInPlace = function (other) {
  2104. if (other.x < this.x)
  2105. this.x = other.x;
  2106. if (other.y < this.y)
  2107. this.y = other.y;
  2108. if (other.z < this.z)
  2109. this.z = other.z;
  2110. if (other.w < this.w)
  2111. this.w = other.w;
  2112. return this;
  2113. };
  2114. /**
  2115. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones.
  2116. */
  2117. Vector4.prototype.MaximizeInPlace = function (other) {
  2118. if (other.x > this.x)
  2119. this.x = other.x;
  2120. if (other.y > this.y)
  2121. this.y = other.y;
  2122. if (other.z > this.z)
  2123. this.z = other.z;
  2124. if (other.w > this.w)
  2125. this.w = other.w;
  2126. return this;
  2127. };
  2128. // Properties
  2129. /**
  2130. * Returns the Vector4 length (float).
  2131. */
  2132. Vector4.prototype.length = function () {
  2133. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  2134. };
  2135. /**
  2136. * Returns the Vector4 squared length (float).
  2137. */
  2138. Vector4.prototype.lengthSquared = function () {
  2139. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  2140. };
  2141. // Methods
  2142. /**
  2143. * Normalizes in place the Vector4.
  2144. * Returns the updated Vector4.
  2145. */
  2146. Vector4.prototype.normalize = function () {
  2147. var len = this.length();
  2148. if (len === 0)
  2149. return this;
  2150. var num = 1.0 / len;
  2151. this.x *= num;
  2152. this.y *= num;
  2153. this.z *= num;
  2154. this.w *= num;
  2155. return this;
  2156. };
  2157. /**
  2158. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  2159. */
  2160. Vector4.prototype.toVector3 = function () {
  2161. return new Vector3(this.x, this.y, this.z);
  2162. };
  2163. /**
  2164. * Returns a new Vector4 copied from the current one.
  2165. */
  2166. Vector4.prototype.clone = function () {
  2167. return new Vector4(this.x, this.y, this.z, this.w);
  2168. };
  2169. /**
  2170. * Updates the current Vector4 with the passed one coordinates.
  2171. * Returns the updated Vector4.
  2172. */
  2173. Vector4.prototype.copyFrom = function (source) {
  2174. this.x = source.x;
  2175. this.y = source.y;
  2176. this.z = source.z;
  2177. this.w = source.w;
  2178. return this;
  2179. };
  2180. /**
  2181. * Updates the current Vector4 coordinates with the passed floats.
  2182. * Returns the updated Vector4.
  2183. */
  2184. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  2185. this.x = x;
  2186. this.y = y;
  2187. this.z = z;
  2188. this.w = w;
  2189. return this;
  2190. };
  2191. /**
  2192. * Updates the current Vector4 coordinates with the passed floats.
  2193. * Returns the updated Vector4.
  2194. */
  2195. Vector4.prototype.set = function (x, y, z, w) {
  2196. return this.copyFromFloats(x, y, z, w);
  2197. };
  2198. // Statics
  2199. /**
  2200. * Returns a new Vector4 set from the starting index of the passed array.
  2201. */
  2202. Vector4.FromArray = function (array, offset) {
  2203. if (!offset) {
  2204. offset = 0;
  2205. }
  2206. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2207. };
  2208. /**
  2209. * Updates the passed vector "result" from the starting index of the passed array.
  2210. */
  2211. Vector4.FromArrayToRef = function (array, offset, result) {
  2212. result.x = array[offset];
  2213. result.y = array[offset + 1];
  2214. result.z = array[offset + 2];
  2215. result.w = array[offset + 3];
  2216. };
  2217. /**
  2218. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  2219. */
  2220. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  2221. Vector4.FromArrayToRef(array, offset, result);
  2222. };
  2223. /**
  2224. * Updates the passed vector "result" coordinates from the passed floats.
  2225. */
  2226. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  2227. result.x = x;
  2228. result.y = y;
  2229. result.z = z;
  2230. result.w = w;
  2231. };
  2232. /**
  2233. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  2234. */
  2235. Vector4.Zero = function () {
  2236. return new Vector4(0.0, 0.0, 0.0, 0.0);
  2237. };
  2238. /**
  2239. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  2240. */
  2241. Vector4.One = function () {
  2242. return new Vector4(1.0, 1.0, 1.0, 1.0);
  2243. };
  2244. /**
  2245. * Returns a new normalized Vector4 from the passed one.
  2246. */
  2247. Vector4.Normalize = function (vector) {
  2248. var result = Vector4.Zero();
  2249. Vector4.NormalizeToRef(vector, result);
  2250. return result;
  2251. };
  2252. /**
  2253. * Updates the passed vector "result" from the normalization of the passed one.
  2254. */
  2255. Vector4.NormalizeToRef = function (vector, result) {
  2256. result.copyFrom(vector);
  2257. result.normalize();
  2258. };
  2259. Vector4.Minimize = function (left, right) {
  2260. var min = left.clone();
  2261. min.MinimizeInPlace(right);
  2262. return min;
  2263. };
  2264. Vector4.Maximize = function (left, right) {
  2265. var max = left.clone();
  2266. max.MaximizeInPlace(right);
  2267. return max;
  2268. };
  2269. /**
  2270. * Returns the distance (float) between the vectors "value1" and "value2".
  2271. */
  2272. Vector4.Distance = function (value1, value2) {
  2273. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  2274. };
  2275. /**
  2276. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2277. */
  2278. Vector4.DistanceSquared = function (value1, value2) {
  2279. var x = value1.x - value2.x;
  2280. var y = value1.y - value2.y;
  2281. var z = value1.z - value2.z;
  2282. var w = value1.w - value2.w;
  2283. return (x * x) + (y * y) + (z * z) + (w * w);
  2284. };
  2285. /**
  2286. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  2287. */
  2288. Vector4.Center = function (value1, value2) {
  2289. var center = value1.add(value2);
  2290. center.scaleInPlace(0.5);
  2291. return center;
  2292. };
  2293. /**
  2294. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  2295. * This methods computes transformed normalized direction vectors only.
  2296. */
  2297. Vector4.TransformNormal = function (vector, transformation) {
  2298. var result = Vector4.Zero();
  2299. Vector4.TransformNormalToRef(vector, transformation, result);
  2300. return result;
  2301. };
  2302. /**
  2303. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  2304. * This methods computes transformed normalized direction vectors only.
  2305. */
  2306. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  2307. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  2308. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  2309. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  2310. result.x = x;
  2311. result.y = y;
  2312. result.z = z;
  2313. result.w = vector.w;
  2314. };
  2315. /**
  2316. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  2317. * This methods computes transformed normalized direction vectors only.
  2318. */
  2319. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  2320. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  2321. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  2322. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  2323. result.w = w;
  2324. };
  2325. return Vector4;
  2326. }());
  2327. BABYLON.Vector4 = Vector4;
  2328. var Size = /** @class */ (function () {
  2329. /**
  2330. * Creates a Size object from the passed width and height (floats).
  2331. */
  2332. function Size(width, height) {
  2333. this.width = width;
  2334. this.height = height;
  2335. }
  2336. // Returns a string with the Size width and height.
  2337. Size.prototype.toString = function () {
  2338. return "{W: " + this.width + ", H: " + this.height + "}";
  2339. };
  2340. /**
  2341. * Returns the string "Size"
  2342. */
  2343. Size.prototype.getClassName = function () {
  2344. return "Size";
  2345. };
  2346. /**
  2347. * Returns the Size hash code.
  2348. */
  2349. Size.prototype.getHashCode = function () {
  2350. var hash = this.width || 0;
  2351. hash = (hash * 397) ^ (this.height || 0);
  2352. return hash;
  2353. };
  2354. /**
  2355. * Updates the current size from the passed one.
  2356. * Returns the updated Size.
  2357. */
  2358. Size.prototype.copyFrom = function (src) {
  2359. this.width = src.width;
  2360. this.height = src.height;
  2361. };
  2362. /**
  2363. * Updates in place the current Size from the passed floats.
  2364. * Returns the updated Size.
  2365. */
  2366. Size.prototype.copyFromFloats = function (width, height) {
  2367. this.width = width;
  2368. this.height = height;
  2369. return this;
  2370. };
  2371. /**
  2372. * Updates in place the current Size from the passed floats.
  2373. * Returns the updated Size.
  2374. */
  2375. Size.prototype.set = function (width, height) {
  2376. return this.copyFromFloats(width, height);
  2377. };
  2378. /**
  2379. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  2380. */
  2381. Size.prototype.multiplyByFloats = function (w, h) {
  2382. return new Size(this.width * w, this.height * h);
  2383. };
  2384. /**
  2385. * Returns a new Size copied from the passed one.
  2386. */
  2387. Size.prototype.clone = function () {
  2388. return new Size(this.width, this.height);
  2389. };
  2390. /**
  2391. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  2392. */
  2393. Size.prototype.equals = function (other) {
  2394. if (!other) {
  2395. return false;
  2396. }
  2397. return (this.width === other.width) && (this.height === other.height);
  2398. };
  2399. Object.defineProperty(Size.prototype, "surface", {
  2400. /**
  2401. * Returns the surface of the Size : width * height (float).
  2402. */
  2403. get: function () {
  2404. return this.width * this.height;
  2405. },
  2406. enumerable: true,
  2407. configurable: true
  2408. });
  2409. /**
  2410. * Returns a new Size set to (0.0, 0.0)
  2411. */
  2412. Size.Zero = function () {
  2413. return new Size(0.0, 0.0);
  2414. };
  2415. /**
  2416. * Returns a new Size set as the addition result of the current Size and the passed one.
  2417. */
  2418. Size.prototype.add = function (otherSize) {
  2419. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  2420. return r;
  2421. };
  2422. /**
  2423. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  2424. */
  2425. Size.prototype.subtract = function (otherSize) {
  2426. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  2427. return r;
  2428. };
  2429. /**
  2430. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  2431. */
  2432. Size.Lerp = function (start, end, amount) {
  2433. var w = start.width + ((end.width - start.width) * amount);
  2434. var h = start.height + ((end.height - start.height) * amount);
  2435. return new Size(w, h);
  2436. };
  2437. return Size;
  2438. }());
  2439. BABYLON.Size = Size;
  2440. var Quaternion = /** @class */ (function () {
  2441. /**
  2442. * Creates a new Quaternion from the passed floats.
  2443. */
  2444. function Quaternion(x, y, z, w) {
  2445. if (x === void 0) { x = 0.0; }
  2446. if (y === void 0) { y = 0.0; }
  2447. if (z === void 0) { z = 0.0; }
  2448. if (w === void 0) { w = 1.0; }
  2449. this.x = x;
  2450. this.y = y;
  2451. this.z = z;
  2452. this.w = w;
  2453. }
  2454. /**
  2455. * Returns a string with the Quaternion coordinates.
  2456. */
  2457. Quaternion.prototype.toString = function () {
  2458. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  2459. };
  2460. /**
  2461. * Returns the string "Quaternion".
  2462. */
  2463. Quaternion.prototype.getClassName = function () {
  2464. return "Quaternion";
  2465. };
  2466. /**
  2467. * Returns the Quaternion hash code.
  2468. */
  2469. Quaternion.prototype.getHashCode = function () {
  2470. var hash = this.x || 0;
  2471. hash = (hash * 397) ^ (this.y || 0);
  2472. hash = (hash * 397) ^ (this.z || 0);
  2473. hash = (hash * 397) ^ (this.w || 0);
  2474. return hash;
  2475. };
  2476. /**
  2477. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  2478. */
  2479. Quaternion.prototype.asArray = function () {
  2480. return [this.x, this.y, this.z, this.w];
  2481. };
  2482. /**
  2483. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  2484. */
  2485. Quaternion.prototype.equals = function (otherQuaternion) {
  2486. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  2487. };
  2488. /**
  2489. * Returns a new Quaternion copied from the current one.
  2490. */
  2491. Quaternion.prototype.clone = function () {
  2492. return new Quaternion(this.x, this.y, this.z, this.w);
  2493. };
  2494. /**
  2495. * Updates the current Quaternion from the passed one coordinates.
  2496. * Returns the updated Quaterion.
  2497. */
  2498. Quaternion.prototype.copyFrom = function (other) {
  2499. this.x = other.x;
  2500. this.y = other.y;
  2501. this.z = other.z;
  2502. this.w = other.w;
  2503. return this;
  2504. };
  2505. /**
  2506. * Updates the current Quaternion from the passed float coordinates.
  2507. * Returns the updated Quaterion.
  2508. */
  2509. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  2510. this.x = x;
  2511. this.y = y;
  2512. this.z = z;
  2513. this.w = w;
  2514. return this;
  2515. };
  2516. /**
  2517. * Updates the current Quaternion from the passed float coordinates.
  2518. * Returns the updated Quaterion.
  2519. */
  2520. Quaternion.prototype.set = function (x, y, z, w) {
  2521. return this.copyFromFloats(x, y, z, w);
  2522. };
  2523. /**
  2524. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  2525. */
  2526. Quaternion.prototype.add = function (other) {
  2527. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  2528. };
  2529. /**
  2530. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  2531. */
  2532. Quaternion.prototype.subtract = function (other) {
  2533. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  2534. };
  2535. /**
  2536. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  2537. */
  2538. Quaternion.prototype.scale = function (value) {
  2539. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  2540. };
  2541. /**
  2542. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  2543. */
  2544. Quaternion.prototype.multiply = function (q1) {
  2545. var result = new Quaternion(0, 0, 0, 1.0);
  2546. this.multiplyToRef(q1, result);
  2547. return result;
  2548. };
  2549. /**
  2550. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  2551. * Returns the current Quaternion.
  2552. */
  2553. Quaternion.prototype.multiplyToRef = function (q1, result) {
  2554. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  2555. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  2556. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  2557. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  2558. result.copyFromFloats(x, y, z, w);
  2559. return this;
  2560. };
  2561. /**
  2562. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  2563. * Returns the updated Quaternion.
  2564. */
  2565. Quaternion.prototype.multiplyInPlace = function (q1) {
  2566. this.multiplyToRef(q1, this);
  2567. return this;
  2568. };
  2569. /**
  2570. * Sets the passed "ref" with the conjugation of the current Quaternion.
  2571. * Returns the current Quaternion.
  2572. */
  2573. Quaternion.prototype.conjugateToRef = function (ref) {
  2574. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  2575. return this;
  2576. };
  2577. /**
  2578. * Conjugates in place the current Quaternion.
  2579. * Returns the updated Quaternion.
  2580. */
  2581. Quaternion.prototype.conjugateInPlace = function () {
  2582. this.x *= -1;
  2583. this.y *= -1;
  2584. this.z *= -1;
  2585. return this;
  2586. };
  2587. /**
  2588. * Returns a new Quaternion as the conjugate of the current Quaternion.
  2589. */
  2590. Quaternion.prototype.conjugate = function () {
  2591. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  2592. return result;
  2593. };
  2594. /**
  2595. * Returns the Quaternion length (float).
  2596. */
  2597. Quaternion.prototype.length = function () {
  2598. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  2599. };
  2600. /**
  2601. * Normalize in place the current Quaternion.
  2602. * Returns the updated Quaternion.
  2603. */
  2604. Quaternion.prototype.normalize = function () {
  2605. var length = 1.0 / this.length();
  2606. this.x *= length;
  2607. this.y *= length;
  2608. this.z *= length;
  2609. this.w *= length;
  2610. return this;
  2611. };
  2612. /**
  2613. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion.
  2614. */
  2615. Quaternion.prototype.toEulerAngles = function (order) {
  2616. if (order === void 0) { order = "YZX"; }
  2617. var result = Vector3.Zero();
  2618. this.toEulerAnglesToRef(result, order);
  2619. return result;
  2620. };
  2621. /**
  2622. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion.
  2623. * Returns the current Quaternion.
  2624. */
  2625. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  2626. if (order === void 0) { order = "YZX"; }
  2627. var qz = this.z;
  2628. var qx = this.x;
  2629. var qy = this.y;
  2630. var qw = this.w;
  2631. var sqw = qw * qw;
  2632. var sqz = qz * qz;
  2633. var sqx = qx * qx;
  2634. var sqy = qy * qy;
  2635. var zAxisY = qy * qz - qx * qw;
  2636. var limit = .4999999;
  2637. if (zAxisY < -limit) {
  2638. result.y = 2 * Math.atan2(qy, qw);
  2639. result.x = Math.PI / 2;
  2640. result.z = 0;
  2641. }
  2642. else if (zAxisY > limit) {
  2643. result.y = 2 * Math.atan2(qy, qw);
  2644. result.x = -Math.PI / 2;
  2645. result.z = 0;
  2646. }
  2647. else {
  2648. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  2649. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  2650. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  2651. }
  2652. return this;
  2653. };
  2654. /**
  2655. * Updates the passed rotation matrix with the current Quaternion values.
  2656. * Returns the current Quaternion.
  2657. */
  2658. Quaternion.prototype.toRotationMatrix = function (result) {
  2659. var xx = this.x * this.x;
  2660. var yy = this.y * this.y;
  2661. var zz = this.z * this.z;
  2662. var xy = this.x * this.y;
  2663. var zw = this.z * this.w;
  2664. var zx = this.z * this.x;
  2665. var yw = this.y * this.w;
  2666. var yz = this.y * this.z;
  2667. var xw = this.x * this.w;
  2668. result.m[0] = 1.0 - (2.0 * (yy + zz));
  2669. result.m[1] = 2.0 * (xy + zw);
  2670. result.m[2] = 2.0 * (zx - yw);
  2671. result.m[3] = 0;
  2672. result.m[4] = 2.0 * (xy - zw);
  2673. result.m[5] = 1.0 - (2.0 * (zz + xx));
  2674. result.m[6] = 2.0 * (yz + xw);
  2675. result.m[7] = 0;
  2676. result.m[8] = 2.0 * (zx + yw);
  2677. result.m[9] = 2.0 * (yz - xw);
  2678. result.m[10] = 1.0 - (2.0 * (yy + xx));
  2679. result.m[11] = 0;
  2680. result.m[12] = 0;
  2681. result.m[13] = 0;
  2682. result.m[14] = 0;
  2683. result.m[15] = 1.0;
  2684. result._markAsUpdated();
  2685. return this;
  2686. };
  2687. /**
  2688. * Updates the current Quaternion from the passed rotation matrix values.
  2689. * Returns the updated Quaternion.
  2690. */
  2691. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  2692. Quaternion.FromRotationMatrixToRef(matrix, this);
  2693. return this;
  2694. };
  2695. // Statics
  2696. /**
  2697. * Returns a new Quaternion set from the passed rotation matrix values.
  2698. */
  2699. Quaternion.FromRotationMatrix = function (matrix) {
  2700. var result = new Quaternion();
  2701. Quaternion.FromRotationMatrixToRef(matrix, result);
  2702. return result;
  2703. };
  2704. /**
  2705. * Updates the passed quaternion "result" with the passed rotation matrix values.
  2706. */
  2707. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  2708. var data = matrix.m;
  2709. var m11 = data[0], m12 = data[4], m13 = data[8];
  2710. var m21 = data[1], m22 = data[5], m23 = data[9];
  2711. var m31 = data[2], m32 = data[6], m33 = data[10];
  2712. var trace = m11 + m22 + m33;
  2713. var s;
  2714. if (trace > 0) {
  2715. s = 0.5 / Math.sqrt(trace + 1.0);
  2716. result.w = 0.25 / s;
  2717. result.x = (m32 - m23) * s;
  2718. result.y = (m13 - m31) * s;
  2719. result.z = (m21 - m12) * s;
  2720. }
  2721. else if (m11 > m22 && m11 > m33) {
  2722. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  2723. result.w = (m32 - m23) / s;
  2724. result.x = 0.25 * s;
  2725. result.y = (m12 + m21) / s;
  2726. result.z = (m13 + m31) / s;
  2727. }
  2728. else if (m22 > m33) {
  2729. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  2730. result.w = (m13 - m31) / s;
  2731. result.x = (m12 + m21) / s;
  2732. result.y = 0.25 * s;
  2733. result.z = (m23 + m32) / s;
  2734. }
  2735. else {
  2736. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  2737. result.w = (m21 - m12) / s;
  2738. result.x = (m13 + m31) / s;
  2739. result.y = (m23 + m32) / s;
  2740. result.z = 0.25 * s;
  2741. }
  2742. };
  2743. /**
  2744. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  2745. */
  2746. Quaternion.Zero = function () {
  2747. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  2748. };
  2749. /**
  2750. * Returns a new Quaternion as the inverted current Quaternion.
  2751. */
  2752. Quaternion.Inverse = function (q) {
  2753. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  2754. };
  2755. /**
  2756. * Returns the identity Quaternion.
  2757. */
  2758. Quaternion.Identity = function () {
  2759. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  2760. };
  2761. Quaternion.IsIdentity = function (quaternion) {
  2762. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  2763. };
  2764. /**
  2765. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  2766. */
  2767. Quaternion.RotationAxis = function (axis, angle) {
  2768. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  2769. };
  2770. /**
  2771. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  2772. */
  2773. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  2774. var sin = Math.sin(angle / 2);
  2775. axis.normalize();
  2776. result.w = Math.cos(angle / 2);
  2777. result.x = axis.x * sin;
  2778. result.y = axis.y * sin;
  2779. result.z = axis.z * sin;
  2780. return result;
  2781. };
  2782. /**
  2783. * Retuns a new Quaternion set from the starting index of the passed array.
  2784. */
  2785. Quaternion.FromArray = function (array, offset) {
  2786. if (!offset) {
  2787. offset = 0;
  2788. }
  2789. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2790. };
  2791. /**
  2792. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  2793. */
  2794. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  2795. var q = new Quaternion();
  2796. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  2797. return q;
  2798. };
  2799. /**
  2800. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  2801. */
  2802. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  2803. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  2804. var halfRoll = roll * 0.5;
  2805. var halfPitch = pitch * 0.5;
  2806. var halfYaw = yaw * 0.5;
  2807. var sinRoll = Math.sin(halfRoll);
  2808. var cosRoll = Math.cos(halfRoll);
  2809. var sinPitch = Math.sin(halfPitch);
  2810. var cosPitch = Math.cos(halfPitch);
  2811. var sinYaw = Math.sin(halfYaw);
  2812. var cosYaw = Math.cos(halfYaw);
  2813. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  2814. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  2815. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  2816. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  2817. };
  2818. /**
  2819. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  2820. */
  2821. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  2822. var result = new Quaternion();
  2823. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  2824. return result;
  2825. };
  2826. /**
  2827. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  2828. */
  2829. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  2830. // Produces a quaternion from Euler angles in the z-x-z orientation
  2831. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  2832. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  2833. var halfBeta = beta * 0.5;
  2834. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  2835. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  2836. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  2837. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  2838. };
  2839. /**
  2840. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  2841. * cf to Vector3.RotationFromAxis() documentation.
  2842. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2843. */
  2844. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  2845. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  2846. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  2847. return quat;
  2848. };
  2849. /**
  2850. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  2851. * cf to Vector3.RotationFromAxis() documentation.
  2852. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2853. */
  2854. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  2855. var rotMat = MathTmp.Matrix[0];
  2856. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  2857. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  2858. };
  2859. Quaternion.Slerp = function (left, right, amount) {
  2860. var result = Quaternion.Identity();
  2861. Quaternion.SlerpToRef(left, right, amount, result);
  2862. return result;
  2863. };
  2864. Quaternion.SlerpToRef = function (left, right, amount, result) {
  2865. var num2;
  2866. var num3;
  2867. var num = amount;
  2868. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  2869. var flag = false;
  2870. if (num4 < 0) {
  2871. flag = true;
  2872. num4 = -num4;
  2873. }
  2874. if (num4 > 0.999999) {
  2875. num3 = 1 - num;
  2876. num2 = flag ? -num : num;
  2877. }
  2878. else {
  2879. var num5 = Math.acos(num4);
  2880. var num6 = (1.0 / Math.sin(num5));
  2881. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  2882. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  2883. }
  2884. result.x = (num3 * left.x) + (num2 * right.x);
  2885. result.y = (num3 * left.y) + (num2 * right.y);
  2886. result.z = (num3 * left.z) + (num2 * right.z);
  2887. result.w = (num3 * left.w) + (num2 * right.w);
  2888. };
  2889. /**
  2890. * Returns a new Quaternion located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  2891. */
  2892. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2893. var squared = amount * amount;
  2894. var cubed = amount * squared;
  2895. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2896. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2897. var part3 = (cubed - (2.0 * squared)) + amount;
  2898. var part4 = cubed - squared;
  2899. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2900. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2901. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  2902. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  2903. return new Quaternion(x, y, z, w);
  2904. };
  2905. return Quaternion;
  2906. }());
  2907. BABYLON.Quaternion = Quaternion;
  2908. var Matrix = /** @class */ (function () {
  2909. function Matrix() {
  2910. this._isIdentity = false;
  2911. this._isIdentityDirty = true;
  2912. this.m = new Float32Array(16);
  2913. this._markAsUpdated();
  2914. }
  2915. Matrix.prototype._markAsUpdated = function () {
  2916. this.updateFlag = Matrix._updateFlagSeed++;
  2917. this._isIdentityDirty = true;
  2918. };
  2919. // Properties
  2920. /**
  2921. * Boolean : True is the matrix is the identity matrix
  2922. */
  2923. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  2924. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  2925. if (this._isIdentityDirty) {
  2926. this._isIdentityDirty = false;
  2927. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  2928. this._isIdentity = false;
  2929. }
  2930. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  2931. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  2932. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  2933. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  2934. this._isIdentity = false;
  2935. }
  2936. else {
  2937. this._isIdentity = true;
  2938. }
  2939. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  2940. this._isIdentity = false;
  2941. }
  2942. }
  2943. return this._isIdentity;
  2944. };
  2945. /**
  2946. * Returns the matrix determinant (float).
  2947. */
  2948. Matrix.prototype.determinant = function () {
  2949. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  2950. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  2951. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  2952. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  2953. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  2954. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  2955. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  2956. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  2957. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  2958. };
  2959. // Methods
  2960. /**
  2961. * Returns the matrix underlying array.
  2962. */
  2963. Matrix.prototype.toArray = function () {
  2964. return this.m;
  2965. };
  2966. /**
  2967. * Returns the matrix underlying array.
  2968. */
  2969. Matrix.prototype.asArray = function () {
  2970. return this.toArray();
  2971. };
  2972. /**
  2973. * Inverts in place the Matrix.
  2974. * Returns the Matrix inverted.
  2975. */
  2976. Matrix.prototype.invert = function () {
  2977. this.invertToRef(this);
  2978. return this;
  2979. };
  2980. /**
  2981. * Sets all the matrix elements to zero.
  2982. * Returns the Matrix.
  2983. */
  2984. Matrix.prototype.reset = function () {
  2985. for (var index = 0; index < 16; index++) {
  2986. this.m[index] = 0.0;
  2987. }
  2988. this._markAsUpdated();
  2989. return this;
  2990. };
  2991. /**
  2992. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  2993. */
  2994. Matrix.prototype.add = function (other) {
  2995. var result = new Matrix();
  2996. this.addToRef(other, result);
  2997. return result;
  2998. };
  2999. /**
  3000. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  3001. * Returns the Matrix.
  3002. */
  3003. Matrix.prototype.addToRef = function (other, result) {
  3004. for (var index = 0; index < 16; index++) {
  3005. result.m[index] = this.m[index] + other.m[index];
  3006. }
  3007. result._markAsUpdated();
  3008. return this;
  3009. };
  3010. /**
  3011. * Adds in place the passed matrix to the current Matrix.
  3012. * Returns the updated Matrix.
  3013. */
  3014. Matrix.prototype.addToSelf = function (other) {
  3015. for (var index = 0; index < 16; index++) {
  3016. this.m[index] += other.m[index];
  3017. }
  3018. this._markAsUpdated();
  3019. return this;
  3020. };
  3021. /**
  3022. * Sets the passed matrix with the current inverted Matrix.
  3023. * Returns the unmodified current Matrix.
  3024. */
  3025. Matrix.prototype.invertToRef = function (other) {
  3026. var l1 = this.m[0];
  3027. var l2 = this.m[1];
  3028. var l3 = this.m[2];
  3029. var l4 = this.m[3];
  3030. var l5 = this.m[4];
  3031. var l6 = this.m[5];
  3032. var l7 = this.m[6];
  3033. var l8 = this.m[7];
  3034. var l9 = this.m[8];
  3035. var l10 = this.m[9];
  3036. var l11 = this.m[10];
  3037. var l12 = this.m[11];
  3038. var l13 = this.m[12];
  3039. var l14 = this.m[13];
  3040. var l15 = this.m[14];
  3041. var l16 = this.m[15];
  3042. var l17 = (l11 * l16) - (l12 * l15);
  3043. var l18 = (l10 * l16) - (l12 * l14);
  3044. var l19 = (l10 * l15) - (l11 * l14);
  3045. var l20 = (l9 * l16) - (l12 * l13);
  3046. var l21 = (l9 * l15) - (l11 * l13);
  3047. var l22 = (l9 * l14) - (l10 * l13);
  3048. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  3049. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  3050. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  3051. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  3052. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  3053. var l28 = (l7 * l16) - (l8 * l15);
  3054. var l29 = (l6 * l16) - (l8 * l14);
  3055. var l30 = (l6 * l15) - (l7 * l14);
  3056. var l31 = (l5 * l16) - (l8 * l13);
  3057. var l32 = (l5 * l15) - (l7 * l13);
  3058. var l33 = (l5 * l14) - (l6 * l13);
  3059. var l34 = (l7 * l12) - (l8 * l11);
  3060. var l35 = (l6 * l12) - (l8 * l10);
  3061. var l36 = (l6 * l11) - (l7 * l10);
  3062. var l37 = (l5 * l12) - (l8 * l9);
  3063. var l38 = (l5 * l11) - (l7 * l9);
  3064. var l39 = (l5 * l10) - (l6 * l9);
  3065. other.m[0] = l23 * l27;
  3066. other.m[4] = l24 * l27;
  3067. other.m[8] = l25 * l27;
  3068. other.m[12] = l26 * l27;
  3069. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  3070. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  3071. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  3072. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  3073. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  3074. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  3075. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  3076. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  3077. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  3078. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  3079. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  3080. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  3081. other._markAsUpdated();
  3082. return this;
  3083. };
  3084. /**
  3085. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  3086. * Returns the updated Matrix.
  3087. */
  3088. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  3089. this.m[12] = x;
  3090. this.m[13] = y;
  3091. this.m[14] = z;
  3092. this._markAsUpdated();
  3093. return this;
  3094. };
  3095. /**
  3096. * Inserts the translation vector in the current Matrix.
  3097. * Returns the updated Matrix.
  3098. */
  3099. Matrix.prototype.setTranslation = function (vector3) {
  3100. this.m[12] = vector3.x;
  3101. this.m[13] = vector3.y;
  3102. this.m[14] = vector3.z;
  3103. this._markAsUpdated();
  3104. return this;
  3105. };
  3106. /**
  3107. * Returns a new Vector3 as the extracted translation from the Matrix.
  3108. */
  3109. Matrix.prototype.getTranslation = function () {
  3110. return new Vector3(this.m[12], this.m[13], this.m[14]);
  3111. };
  3112. /**
  3113. * Fill a Vector3 with the extracted translation from the Matrix.
  3114. */
  3115. Matrix.prototype.getTranslationToRef = function (result) {
  3116. result.x = this.m[12];
  3117. result.y = this.m[13];
  3118. result.z = this.m[14];
  3119. return this;
  3120. };
  3121. /**
  3122. * Remove rotation and scaling part from the Matrix.
  3123. * Returns the updated Matrix.
  3124. */
  3125. Matrix.prototype.removeRotationAndScaling = function () {
  3126. this.setRowFromFloats(0, 1, 0, 0, 0);
  3127. this.setRowFromFloats(1, 0, 1, 0, 0);
  3128. this.setRowFromFloats(2, 0, 0, 1, 0);
  3129. return this;
  3130. };
  3131. /**
  3132. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  3133. */
  3134. Matrix.prototype.multiply = function (other) {
  3135. var result = new Matrix();
  3136. this.multiplyToRef(other, result);
  3137. return result;
  3138. };
  3139. /**
  3140. * Updates the current Matrix from the passed one values.
  3141. * Returns the updated Matrix.
  3142. */
  3143. Matrix.prototype.copyFrom = function (other) {
  3144. for (var index = 0; index < 16; index++) {
  3145. this.m[index] = other.m[index];
  3146. }
  3147. this._markAsUpdated();
  3148. return this;
  3149. };
  3150. /**
  3151. * Populates the passed array from the starting index with the Matrix values.
  3152. * Returns the Matrix.
  3153. */
  3154. Matrix.prototype.copyToArray = function (array, offset) {
  3155. if (offset === void 0) { offset = 0; }
  3156. for (var index = 0; index < 16; index++) {
  3157. array[offset + index] = this.m[index];
  3158. }
  3159. return this;
  3160. };
  3161. /**
  3162. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  3163. */
  3164. Matrix.prototype.multiplyToRef = function (other, result) {
  3165. this.multiplyToArray(other, result.m, 0);
  3166. result._markAsUpdated();
  3167. return this;
  3168. };
  3169. /**
  3170. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  3171. */
  3172. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  3173. var tm0 = this.m[0];
  3174. var tm1 = this.m[1];
  3175. var tm2 = this.m[2];
  3176. var tm3 = this.m[3];
  3177. var tm4 = this.m[4];
  3178. var tm5 = this.m[5];
  3179. var tm6 = this.m[6];
  3180. var tm7 = this.m[7];
  3181. var tm8 = this.m[8];
  3182. var tm9 = this.m[9];
  3183. var tm10 = this.m[10];
  3184. var tm11 = this.m[11];
  3185. var tm12 = this.m[12];
  3186. var tm13 = this.m[13];
  3187. var tm14 = this.m[14];
  3188. var tm15 = this.m[15];
  3189. var om0 = other.m[0];
  3190. var om1 = other.m[1];
  3191. var om2 = other.m[2];
  3192. var om3 = other.m[3];
  3193. var om4 = other.m[4];
  3194. var om5 = other.m[5];
  3195. var om6 = other.m[6];
  3196. var om7 = other.m[7];
  3197. var om8 = other.m[8];
  3198. var om9 = other.m[9];
  3199. var om10 = other.m[10];
  3200. var om11 = other.m[11];
  3201. var om12 = other.m[12];
  3202. var om13 = other.m[13];
  3203. var om14 = other.m[14];
  3204. var om15 = other.m[15];
  3205. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  3206. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  3207. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  3208. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  3209. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  3210. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  3211. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  3212. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  3213. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  3214. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  3215. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  3216. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  3217. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  3218. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  3219. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  3220. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  3221. return this;
  3222. };
  3223. /**
  3224. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  3225. */
  3226. Matrix.prototype.equals = function (value) {
  3227. return value &&
  3228. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  3229. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  3230. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  3231. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  3232. };
  3233. /**
  3234. * Returns a new Matrix from the current Matrix.
  3235. */
  3236. Matrix.prototype.clone = function () {
  3237. 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]);
  3238. };
  3239. /**
  3240. * Returns the string "Matrix"
  3241. */
  3242. Matrix.prototype.getClassName = function () {
  3243. return "Matrix";
  3244. };
  3245. /**
  3246. * Returns the Matrix hash code.
  3247. */
  3248. Matrix.prototype.getHashCode = function () {
  3249. var hash = this.m[0] || 0;
  3250. for (var i = 1; i < 16; i++) {
  3251. hash = (hash * 397) ^ (this.m[i] || 0);
  3252. }
  3253. return hash;
  3254. };
  3255. /**
  3256. * Decomposes the current Matrix into :
  3257. * - a scale vector3 passed as a reference to update,
  3258. * - a rotation quaternion passed as a reference to update,
  3259. * - a translation vector3 passed as a reference to update.
  3260. * Returns the boolean `true`.
  3261. */
  3262. Matrix.prototype.decompose = function (scale, rotation, translation) {
  3263. translation.x = this.m[12];
  3264. translation.y = this.m[13];
  3265. translation.z = this.m[14];
  3266. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  3267. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  3268. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  3269. if (this.determinant() <= 0) {
  3270. scale.y *= -1;
  3271. }
  3272. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  3273. rotation.x = 0;
  3274. rotation.y = 0;
  3275. rotation.z = 0;
  3276. rotation.w = 1;
  3277. return false;
  3278. }
  3279. 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]);
  3280. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  3281. return true;
  3282. };
  3283. /**
  3284. * Returns a new Matrix as the extracted rotation matrix from the current one.
  3285. */
  3286. Matrix.prototype.getRotationMatrix = function () {
  3287. var result = Matrix.Identity();
  3288. this.getRotationMatrixToRef(result);
  3289. return result;
  3290. };
  3291. /**
  3292. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  3293. * Returns the current Matrix.
  3294. */
  3295. Matrix.prototype.getRotationMatrixToRef = function (result) {
  3296. var m = this.m;
  3297. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  3298. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  3299. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  3300. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  3301. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  3302. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  3303. 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);
  3304. return this;
  3305. };
  3306. // Statics
  3307. /**
  3308. * Returns a new Matrix set from the starting index of the passed array.
  3309. */
  3310. Matrix.FromArray = function (array, offset) {
  3311. var result = new Matrix();
  3312. if (!offset) {
  3313. offset = 0;
  3314. }
  3315. Matrix.FromArrayToRef(array, offset, result);
  3316. return result;
  3317. };
  3318. /**
  3319. * Sets the passed "result" matrix from the starting index of the passed array.
  3320. */
  3321. Matrix.FromArrayToRef = function (array, offset, result) {
  3322. for (var index = 0; index < 16; index++) {
  3323. result.m[index] = array[index + offset];
  3324. }
  3325. result._markAsUpdated();
  3326. };
  3327. /**
  3328. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  3329. */
  3330. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  3331. for (var index = 0; index < 16; index++) {
  3332. result.m[index] = array[index + offset] * scale;
  3333. }
  3334. result._markAsUpdated();
  3335. };
  3336. /**
  3337. * Sets the passed matrix "result" with the 16 passed floats.
  3338. */
  3339. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  3340. result.m[0] = initialM11;
  3341. result.m[1] = initialM12;
  3342. result.m[2] = initialM13;
  3343. result.m[3] = initialM14;
  3344. result.m[4] = initialM21;
  3345. result.m[5] = initialM22;
  3346. result.m[6] = initialM23;
  3347. result.m[7] = initialM24;
  3348. result.m[8] = initialM31;
  3349. result.m[9] = initialM32;
  3350. result.m[10] = initialM33;
  3351. result.m[11] = initialM34;
  3352. result.m[12] = initialM41;
  3353. result.m[13] = initialM42;
  3354. result.m[14] = initialM43;
  3355. result.m[15] = initialM44;
  3356. result._markAsUpdated();
  3357. };
  3358. /**
  3359. * Returns the index-th row of the current matrix as a new Vector4.
  3360. */
  3361. Matrix.prototype.getRow = function (index) {
  3362. if (index < 0 || index > 3) {
  3363. return null;
  3364. }
  3365. var i = index * 4;
  3366. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  3367. };
  3368. /**
  3369. * Sets the index-th row of the current matrix with the passed Vector4 values.
  3370. * Returns the updated Matrix.
  3371. */
  3372. Matrix.prototype.setRow = function (index, row) {
  3373. if (index < 0 || index > 3) {
  3374. return this;
  3375. }
  3376. var i = index * 4;
  3377. this.m[i + 0] = row.x;
  3378. this.m[i + 1] = row.y;
  3379. this.m[i + 2] = row.z;
  3380. this.m[i + 3] = row.w;
  3381. this._markAsUpdated();
  3382. return this;
  3383. };
  3384. /**
  3385. * Compute the transpose of the matrix.
  3386. * Returns a new Matrix.
  3387. */
  3388. Matrix.prototype.transpose = function () {
  3389. return Matrix.Transpose(this);
  3390. };
  3391. /**
  3392. * Compute the transpose of the matrix.
  3393. * Returns the current matrix.
  3394. */
  3395. Matrix.prototype.transposeToRef = function (result) {
  3396. Matrix.TransposeToRef(this, result);
  3397. return this;
  3398. };
  3399. /**
  3400. * Sets the index-th row of the current matrix with the passed 4 x float values.
  3401. * Returns the updated Matrix.
  3402. */
  3403. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  3404. if (index < 0 || index > 3) {
  3405. return this;
  3406. }
  3407. var i = index * 4;
  3408. this.m[i + 0] = x;
  3409. this.m[i + 1] = y;
  3410. this.m[i + 2] = z;
  3411. this.m[i + 3] = w;
  3412. this._markAsUpdated();
  3413. return this;
  3414. };
  3415. Object.defineProperty(Matrix, "IdentityReadOnly", {
  3416. /**
  3417. * Static identity matrix to be used as readonly matrix
  3418. * Must not be updated.
  3419. */
  3420. get: function () {
  3421. return Matrix._identityReadOnly;
  3422. },
  3423. enumerable: true,
  3424. configurable: true
  3425. });
  3426. /**
  3427. * Returns a new Matrix set from the 16 passed floats.
  3428. */
  3429. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  3430. var result = new Matrix();
  3431. result.m[0] = initialM11;
  3432. result.m[1] = initialM12;
  3433. result.m[2] = initialM13;
  3434. result.m[3] = initialM14;
  3435. result.m[4] = initialM21;
  3436. result.m[5] = initialM22;
  3437. result.m[6] = initialM23;
  3438. result.m[7] = initialM24;
  3439. result.m[8] = initialM31;
  3440. result.m[9] = initialM32;
  3441. result.m[10] = initialM33;
  3442. result.m[11] = initialM34;
  3443. result.m[12] = initialM41;
  3444. result.m[13] = initialM42;
  3445. result.m[14] = initialM43;
  3446. result.m[15] = initialM44;
  3447. return result;
  3448. };
  3449. /**
  3450. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  3451. */
  3452. Matrix.Compose = function (scale, rotation, translation) {
  3453. var result = Matrix.Identity();
  3454. Matrix.ComposeToRef(scale, rotation, translation, result);
  3455. return result;
  3456. };
  3457. /**
  3458. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  3459. */
  3460. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  3461. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  3462. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  3463. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  3464. result.setTranslation(translation);
  3465. };
  3466. /**
  3467. * Returns a new indentity Matrix.
  3468. */
  3469. Matrix.Identity = function () {
  3470. 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);
  3471. };
  3472. /**
  3473. * Sets the passed "result" as an identity matrix.
  3474. */
  3475. Matrix.IdentityToRef = function (result) {
  3476. 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);
  3477. };
  3478. /**
  3479. * Returns a new zero Matrix.
  3480. */
  3481. Matrix.Zero = function () {
  3482. 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);
  3483. };
  3484. /**
  3485. * Returns a new rotation matrix for "angle" radians around the X axis.
  3486. */
  3487. Matrix.RotationX = function (angle) {
  3488. var result = new Matrix();
  3489. Matrix.RotationXToRef(angle, result);
  3490. return result;
  3491. };
  3492. /**
  3493. * Returns a new Matrix as the passed inverted one.
  3494. */
  3495. Matrix.Invert = function (source) {
  3496. var result = new Matrix();
  3497. source.invertToRef(result);
  3498. return result;
  3499. };
  3500. /**
  3501. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  3502. */
  3503. Matrix.RotationXToRef = function (angle, result) {
  3504. var s = Math.sin(angle);
  3505. var c = Math.cos(angle);
  3506. result.m[0] = 1.0;
  3507. result.m[15] = 1.0;
  3508. result.m[5] = c;
  3509. result.m[10] = c;
  3510. result.m[9] = -s;
  3511. result.m[6] = s;
  3512. result.m[1] = 0.0;
  3513. result.m[2] = 0.0;
  3514. result.m[3] = 0.0;
  3515. result.m[4] = 0.0;
  3516. result.m[7] = 0.0;
  3517. result.m[8] = 0.0;
  3518. result.m[11] = 0.0;
  3519. result.m[12] = 0.0;
  3520. result.m[13] = 0.0;
  3521. result.m[14] = 0.0;
  3522. result._markAsUpdated();
  3523. };
  3524. /**
  3525. * Returns a new rotation matrix for "angle" radians around the Y axis.
  3526. */
  3527. Matrix.RotationY = function (angle) {
  3528. var result = new Matrix();
  3529. Matrix.RotationYToRef(angle, result);
  3530. return result;
  3531. };
  3532. /**
  3533. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  3534. */
  3535. Matrix.RotationYToRef = function (angle, result) {
  3536. var s = Math.sin(angle);
  3537. var c = Math.cos(angle);
  3538. result.m[5] = 1.0;
  3539. result.m[15] = 1.0;
  3540. result.m[0] = c;
  3541. result.m[2] = -s;
  3542. result.m[8] = s;
  3543. result.m[10] = c;
  3544. result.m[1] = 0.0;
  3545. result.m[3] = 0.0;
  3546. result.m[4] = 0.0;
  3547. result.m[6] = 0.0;
  3548. result.m[7] = 0.0;
  3549. result.m[9] = 0.0;
  3550. result.m[11] = 0.0;
  3551. result.m[12] = 0.0;
  3552. result.m[13] = 0.0;
  3553. result.m[14] = 0.0;
  3554. result._markAsUpdated();
  3555. };
  3556. /**
  3557. * Returns a new rotation matrix for "angle" radians around the Z axis.
  3558. */
  3559. Matrix.RotationZ = function (angle) {
  3560. var result = new Matrix();
  3561. Matrix.RotationZToRef(angle, result);
  3562. return result;
  3563. };
  3564. /**
  3565. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  3566. */
  3567. Matrix.RotationZToRef = function (angle, result) {
  3568. var s = Math.sin(angle);
  3569. var c = Math.cos(angle);
  3570. result.m[10] = 1.0;
  3571. result.m[15] = 1.0;
  3572. result.m[0] = c;
  3573. result.m[1] = s;
  3574. result.m[4] = -s;
  3575. result.m[5] = c;
  3576. result.m[2] = 0.0;
  3577. result.m[3] = 0.0;
  3578. result.m[6] = 0.0;
  3579. result.m[7] = 0.0;
  3580. result.m[8] = 0.0;
  3581. result.m[9] = 0.0;
  3582. result.m[11] = 0.0;
  3583. result.m[12] = 0.0;
  3584. result.m[13] = 0.0;
  3585. result.m[14] = 0.0;
  3586. result._markAsUpdated();
  3587. };
  3588. /**
  3589. * Returns a new rotation matrix for "angle" radians around the passed axis.
  3590. */
  3591. Matrix.RotationAxis = function (axis, angle) {
  3592. var result = Matrix.Zero();
  3593. Matrix.RotationAxisToRef(axis, angle, result);
  3594. return result;
  3595. };
  3596. /**
  3597. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  3598. */
  3599. Matrix.RotationAxisToRef = function (axis, angle, result) {
  3600. var s = Math.sin(-angle);
  3601. var c = Math.cos(-angle);
  3602. var c1 = 1 - c;
  3603. axis.normalize();
  3604. result.m[0] = (axis.x * axis.x) * c1 + c;
  3605. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  3606. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  3607. result.m[3] = 0.0;
  3608. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  3609. result.m[5] = (axis.y * axis.y) * c1 + c;
  3610. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  3611. result.m[7] = 0.0;
  3612. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  3613. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  3614. result.m[10] = (axis.z * axis.z) * c1 + c;
  3615. result.m[11] = 0.0;
  3616. result.m[15] = 1.0;
  3617. result._markAsUpdated();
  3618. };
  3619. /**
  3620. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  3621. */
  3622. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  3623. var result = new Matrix();
  3624. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  3625. return result;
  3626. };
  3627. /**
  3628. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  3629. */
  3630. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  3631. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  3632. this._tempQuaternion.toRotationMatrix(result);
  3633. };
  3634. /**
  3635. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  3636. */
  3637. Matrix.Scaling = function (x, y, z) {
  3638. var result = Matrix.Zero();
  3639. Matrix.ScalingToRef(x, y, z, result);
  3640. return result;
  3641. };
  3642. /**
  3643. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  3644. */
  3645. Matrix.ScalingToRef = function (x, y, z, result) {
  3646. result.m[0] = x;
  3647. result.m[1] = 0.0;
  3648. result.m[2] = 0.0;
  3649. result.m[3] = 0.0;
  3650. result.m[4] = 0.0;
  3651. result.m[5] = y;
  3652. result.m[6] = 0.0;
  3653. result.m[7] = 0.0;
  3654. result.m[8] = 0.0;
  3655. result.m[9] = 0.0;
  3656. result.m[10] = z;
  3657. result.m[11] = 0.0;
  3658. result.m[12] = 0.0;
  3659. result.m[13] = 0.0;
  3660. result.m[14] = 0.0;
  3661. result.m[15] = 1.0;
  3662. result._markAsUpdated();
  3663. };
  3664. /**
  3665. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  3666. */
  3667. Matrix.Translation = function (x, y, z) {
  3668. var result = Matrix.Identity();
  3669. Matrix.TranslationToRef(x, y, z, result);
  3670. return result;
  3671. };
  3672. /**
  3673. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  3674. */
  3675. Matrix.TranslationToRef = function (x, y, z, result) {
  3676. 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);
  3677. };
  3678. /**
  3679. * Returns a new Matrix whose values are the interpolated values for "gradien" (float) between the ones of the matrices "startValue" and "endValue".
  3680. */
  3681. Matrix.Lerp = function (startValue, endValue, gradient) {
  3682. var result = Matrix.Zero();
  3683. for (var index = 0; index < 16; index++) {
  3684. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  3685. }
  3686. result._markAsUpdated();
  3687. return result;
  3688. };
  3689. /**
  3690. * Returns a new Matrix whose values are computed by :
  3691. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  3692. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  3693. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  3694. */
  3695. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  3696. var startScale = new Vector3(0, 0, 0);
  3697. var startRotation = new Quaternion();
  3698. var startTranslation = new Vector3(0, 0, 0);
  3699. startValue.decompose(startScale, startRotation, startTranslation);
  3700. var endScale = new Vector3(0, 0, 0);
  3701. var endRotation = new Quaternion();
  3702. var endTranslation = new Vector3(0, 0, 0);
  3703. endValue.decompose(endScale, endRotation, endTranslation);
  3704. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  3705. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  3706. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  3707. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  3708. };
  3709. /**
  3710. * 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".
  3711. * This methods works for a Left-Handed system.
  3712. */
  3713. Matrix.LookAtLH = function (eye, target, up) {
  3714. var result = Matrix.Zero();
  3715. Matrix.LookAtLHToRef(eye, target, up, result);
  3716. return result;
  3717. };
  3718. /**
  3719. * 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".
  3720. * This methods works for a Left-Handed system.
  3721. */
  3722. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  3723. // Z axis
  3724. target.subtractToRef(eye, this._zAxis);
  3725. this._zAxis.normalize();
  3726. // X axis
  3727. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  3728. if (this._xAxis.lengthSquared() === 0) {
  3729. this._xAxis.x = 1.0;
  3730. }
  3731. else {
  3732. this._xAxis.normalize();
  3733. }
  3734. // Y axis
  3735. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  3736. this._yAxis.normalize();
  3737. // Eye angles
  3738. var ex = -Vector3.Dot(this._xAxis, eye);
  3739. var ey = -Vector3.Dot(this._yAxis, eye);
  3740. var ez = -Vector3.Dot(this._zAxis, eye);
  3741. 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);
  3742. };
  3743. /**
  3744. * 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".
  3745. * This methods works for a Right-Handed system.
  3746. */
  3747. Matrix.LookAtRH = function (eye, target, up) {
  3748. var result = Matrix.Zero();
  3749. Matrix.LookAtRHToRef(eye, target, up, result);
  3750. return result;
  3751. };
  3752. /**
  3753. * 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".
  3754. * This methods works for a Left-Handed system.
  3755. */
  3756. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  3757. // Z axis
  3758. eye.subtractToRef(target, this._zAxis);
  3759. this._zAxis.normalize();
  3760. // X axis
  3761. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  3762. if (this._xAxis.lengthSquared() === 0) {
  3763. this._xAxis.x = 1.0;
  3764. }
  3765. else {
  3766. this._xAxis.normalize();
  3767. }
  3768. // Y axis
  3769. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  3770. this._yAxis.normalize();
  3771. // Eye angles
  3772. var ex = -Vector3.Dot(this._xAxis, eye);
  3773. var ey = -Vector3.Dot(this._yAxis, eye);
  3774. var ez = -Vector3.Dot(this._zAxis, eye);
  3775. 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);
  3776. };
  3777. /**
  3778. * 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.
  3779. */
  3780. Matrix.OrthoLH = function (width, height, znear, zfar) {
  3781. var matrix = Matrix.Zero();
  3782. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  3783. return matrix;
  3784. };
  3785. /**
  3786. * 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.
  3787. */
  3788. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  3789. var n = znear;
  3790. var f = zfar;
  3791. var a = 2.0 / width;
  3792. var b = 2.0 / height;
  3793. var c = 2.0 / (f - n);
  3794. var d = -(f + n) / (f - n);
  3795. 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);
  3796. };
  3797. /**
  3798. * 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.
  3799. */
  3800. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  3801. var matrix = Matrix.Zero();
  3802. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  3803. return matrix;
  3804. };
  3805. /**
  3806. * 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.
  3807. */
  3808. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  3809. var n = znear;
  3810. var f = zfar;
  3811. var a = 2.0 / (right - left);
  3812. var b = 2.0 / (top - bottom);
  3813. var c = 2.0 / (f - n);
  3814. var d = -(f + n) / (f - n);
  3815. var i0 = (left + right) / (left - right);
  3816. var i1 = (top + bottom) / (bottom - top);
  3817. 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);
  3818. };
  3819. /**
  3820. * 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.
  3821. */
  3822. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  3823. var matrix = Matrix.Zero();
  3824. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  3825. return matrix;
  3826. };
  3827. /**
  3828. * 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.
  3829. */
  3830. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  3831. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  3832. result.m[10] *= -1.0;
  3833. };
  3834. /**
  3835. * 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.
  3836. */
  3837. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  3838. var matrix = Matrix.Zero();
  3839. var n = znear;
  3840. var f = zfar;
  3841. var a = 2.0 * n / width;
  3842. var b = 2.0 * n / height;
  3843. var c = (f + n) / (f - n);
  3844. var d = -2.0 * f * n / (f - n);
  3845. 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);
  3846. return matrix;
  3847. };
  3848. /**
  3849. * 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.
  3850. */
  3851. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  3852. var matrix = Matrix.Zero();
  3853. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  3854. return matrix;
  3855. };
  3856. /**
  3857. * 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.
  3858. */
  3859. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  3860. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  3861. var n = znear;
  3862. var f = zfar;
  3863. var t = 1.0 / (Math.tan(fov * 0.5));
  3864. var a = isVerticalFovFixed ? (t / aspect) : t;
  3865. var b = isVerticalFovFixed ? t : (t * aspect);
  3866. var c = (f + n) / (f - n);
  3867. var d = -2.0 * f * n / (f - n);
  3868. 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);
  3869. };
  3870. /**
  3871. * 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.
  3872. */
  3873. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  3874. var matrix = Matrix.Zero();
  3875. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  3876. return matrix;
  3877. };
  3878. /**
  3879. * 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.
  3880. */
  3881. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  3882. //alternatively this could be expressed as:
  3883. // m = PerspectiveFovLHToRef
  3884. // m[10] *= -1.0;
  3885. // m[11] *= -1.0;
  3886. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  3887. var n = znear;
  3888. var f = zfar;
  3889. var t = 1.0 / (Math.tan(fov * 0.5));
  3890. var a = isVerticalFovFixed ? (t / aspect) : t;
  3891. var b = isVerticalFovFixed ? t : (t * aspect);
  3892. var c = -(f + n) / (f - n);
  3893. var d = -2 * f * n / (f - n);
  3894. 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);
  3895. };
  3896. /**
  3897. * 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.
  3898. */
  3899. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  3900. if (rightHanded === void 0) { rightHanded = false; }
  3901. var rightHandedFactor = rightHanded ? -1 : 1;
  3902. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  3903. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  3904. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  3905. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  3906. var xScale = 2.0 / (leftTan + rightTan);
  3907. var yScale = 2.0 / (upTan + downTan);
  3908. result.m[0] = xScale;
  3909. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  3910. result.m[5] = yScale;
  3911. result.m[6] = result.m[7] = 0.0;
  3912. result.m[8] = ((leftTan - rightTan) * xScale * 0.5); // * rightHandedFactor;
  3913. result.m[9] = -((upTan - downTan) * yScale * 0.5); // * rightHandedFactor;
  3914. //result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  3915. result.m[10] = -zfar / (znear - zfar);
  3916. result.m[11] = 1.0 * rightHandedFactor;
  3917. result.m[12] = result.m[13] = result.m[15] = 0.0;
  3918. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  3919. // result.m[14] = (znear * zfar) / (znear - zfar);
  3920. result._markAsUpdated();
  3921. };
  3922. /**
  3923. * Returns the final transformation matrix : world * view * projection * viewport
  3924. */
  3925. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  3926. var cw = viewport.width;
  3927. var ch = viewport.height;
  3928. var cx = viewport.x;
  3929. var cy = viewport.y;
  3930. 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);
  3931. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  3932. };
  3933. /**
  3934. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  3935. */
  3936. Matrix.GetAsMatrix2x2 = function (matrix) {
  3937. return new Float32Array([
  3938. matrix.m[0], matrix.m[1],
  3939. matrix.m[4], matrix.m[5]
  3940. ]);
  3941. };
  3942. /**
  3943. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  3944. */
  3945. Matrix.GetAsMatrix3x3 = function (matrix) {
  3946. return new Float32Array([
  3947. matrix.m[0], matrix.m[1], matrix.m[2],
  3948. matrix.m[4], matrix.m[5], matrix.m[6],
  3949. matrix.m[8], matrix.m[9], matrix.m[10]
  3950. ]);
  3951. };
  3952. /**
  3953. * Compute the transpose of the passed Matrix.
  3954. * Returns a new Matrix.
  3955. */
  3956. Matrix.Transpose = function (matrix) {
  3957. var result = new Matrix();
  3958. Matrix.TransposeToRef(matrix, result);
  3959. return result;
  3960. };
  3961. /**
  3962. * Compute the transpose of the passed Matrix and store it in the result matrix.
  3963. */
  3964. Matrix.TransposeToRef = function (matrix, result) {
  3965. result.m[0] = matrix.m[0];
  3966. result.m[1] = matrix.m[4];
  3967. result.m[2] = matrix.m[8];
  3968. result.m[3] = matrix.m[12];
  3969. result.m[4] = matrix.m[1];
  3970. result.m[5] = matrix.m[5];
  3971. result.m[6] = matrix.m[9];
  3972. result.m[7] = matrix.m[13];
  3973. result.m[8] = matrix.m[2];
  3974. result.m[9] = matrix.m[6];
  3975. result.m[10] = matrix.m[10];
  3976. result.m[11] = matrix.m[14];
  3977. result.m[12] = matrix.m[3];
  3978. result.m[13] = matrix.m[7];
  3979. result.m[14] = matrix.m[11];
  3980. result.m[15] = matrix.m[15];
  3981. };
  3982. /**
  3983. * Returns a new Matrix as the reflection matrix across the passed plane.
  3984. */
  3985. Matrix.Reflection = function (plane) {
  3986. var matrix = new Matrix();
  3987. Matrix.ReflectionToRef(plane, matrix);
  3988. return matrix;
  3989. };
  3990. /**
  3991. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  3992. */
  3993. Matrix.ReflectionToRef = function (plane, result) {
  3994. plane.normalize();
  3995. var x = plane.normal.x;
  3996. var y = plane.normal.y;
  3997. var z = plane.normal.z;
  3998. var temp = -2 * x;
  3999. var temp2 = -2 * y;
  4000. var temp3 = -2 * z;
  4001. result.m[0] = (temp * x) + 1;
  4002. result.m[1] = temp2 * x;
  4003. result.m[2] = temp3 * x;
  4004. result.m[3] = 0.0;
  4005. result.m[4] = temp * y;
  4006. result.m[5] = (temp2 * y) + 1;
  4007. result.m[6] = temp3 * y;
  4008. result.m[7] = 0.0;
  4009. result.m[8] = temp * z;
  4010. result.m[9] = temp2 * z;
  4011. result.m[10] = (temp3 * z) + 1;
  4012. result.m[11] = 0.0;
  4013. result.m[12] = temp * plane.d;
  4014. result.m[13] = temp2 * plane.d;
  4015. result.m[14] = temp3 * plane.d;
  4016. result.m[15] = 1.0;
  4017. result._markAsUpdated();
  4018. };
  4019. /**
  4020. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  4021. */
  4022. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  4023. result.m[0] = xaxis.x;
  4024. result.m[1] = xaxis.y;
  4025. result.m[2] = xaxis.z;
  4026. result.m[3] = 0.0;
  4027. result.m[4] = yaxis.x;
  4028. result.m[5] = yaxis.y;
  4029. result.m[6] = yaxis.z;
  4030. result.m[7] = 0.0;
  4031. result.m[8] = zaxis.x;
  4032. result.m[9] = zaxis.y;
  4033. result.m[10] = zaxis.z;
  4034. result.m[11] = 0.0;
  4035. result.m[12] = 0.0;
  4036. result.m[13] = 0.0;
  4037. result.m[14] = 0.0;
  4038. result.m[15] = 1.0;
  4039. result._markAsUpdated();
  4040. };
  4041. /**
  4042. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  4043. */
  4044. Matrix.FromQuaternionToRef = function (quat, result) {
  4045. var xx = quat.x * quat.x;
  4046. var yy = quat.y * quat.y;
  4047. var zz = quat.z * quat.z;
  4048. var xy = quat.x * quat.y;
  4049. var zw = quat.z * quat.w;
  4050. var zx = quat.z * quat.x;
  4051. var yw = quat.y * quat.w;
  4052. var yz = quat.y * quat.z;
  4053. var xw = quat.x * quat.w;
  4054. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4055. result.m[1] = 2.0 * (xy + zw);
  4056. result.m[2] = 2.0 * (zx - yw);
  4057. result.m[3] = 0.0;
  4058. result.m[4] = 2.0 * (xy - zw);
  4059. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4060. result.m[6] = 2.0 * (yz + xw);
  4061. result.m[7] = 0.0;
  4062. result.m[8] = 2.0 * (zx + yw);
  4063. result.m[9] = 2.0 * (yz - xw);
  4064. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4065. result.m[11] = 0.0;
  4066. result.m[12] = 0.0;
  4067. result.m[13] = 0.0;
  4068. result.m[14] = 0.0;
  4069. result.m[15] = 1.0;
  4070. result._markAsUpdated();
  4071. };
  4072. Matrix._tempQuaternion = new Quaternion();
  4073. Matrix._xAxis = Vector3.Zero();
  4074. Matrix._yAxis = Vector3.Zero();
  4075. Matrix._zAxis = Vector3.Zero();
  4076. Matrix._updateFlagSeed = 0;
  4077. Matrix._identityReadOnly = Matrix.Identity();
  4078. return Matrix;
  4079. }());
  4080. BABYLON.Matrix = Matrix;
  4081. var Plane = /** @class */ (function () {
  4082. /**
  4083. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  4084. */
  4085. function Plane(a, b, c, d) {
  4086. this.normal = new Vector3(a, b, c);
  4087. this.d = d;
  4088. }
  4089. /**
  4090. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  4091. */
  4092. Plane.prototype.asArray = function () {
  4093. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  4094. };
  4095. // Methods
  4096. /**
  4097. * Returns a new plane copied from the current Plane.
  4098. */
  4099. Plane.prototype.clone = function () {
  4100. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  4101. };
  4102. /**
  4103. * Returns the string "Plane".
  4104. */
  4105. Plane.prototype.getClassName = function () {
  4106. return "Plane";
  4107. };
  4108. /**
  4109. * Returns the Plane hash code.
  4110. */
  4111. Plane.prototype.getHashCode = function () {
  4112. var hash = this.normal.getHashCode();
  4113. hash = (hash * 397) ^ (this.d || 0);
  4114. return hash;
  4115. };
  4116. /**
  4117. * Normalize the current Plane in place.
  4118. * Returns the updated Plane.
  4119. */
  4120. Plane.prototype.normalize = function () {
  4121. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  4122. var magnitude = 0.0;
  4123. if (norm !== 0) {
  4124. magnitude = 1.0 / norm;
  4125. }
  4126. this.normal.x *= magnitude;
  4127. this.normal.y *= magnitude;
  4128. this.normal.z *= magnitude;
  4129. this.d *= magnitude;
  4130. return this;
  4131. };
  4132. /**
  4133. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  4134. */
  4135. Plane.prototype.transform = function (transformation) {
  4136. var transposedMatrix = Matrix.Transpose(transformation);
  4137. var x = this.normal.x;
  4138. var y = this.normal.y;
  4139. var z = this.normal.z;
  4140. var d = this.d;
  4141. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  4142. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  4143. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  4144. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  4145. return new Plane(normalX, normalY, normalZ, finalD);
  4146. };
  4147. /**
  4148. * Returns the dot product (float) of the point coordinates and the plane normal.
  4149. */
  4150. Plane.prototype.dotCoordinate = function (point) {
  4151. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  4152. };
  4153. /**
  4154. * Updates the current Plane from the plane defined by the three passed points.
  4155. * Returns the updated Plane.
  4156. */
  4157. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  4158. var x1 = point2.x - point1.x;
  4159. var y1 = point2.y - point1.y;
  4160. var z1 = point2.z - point1.z;
  4161. var x2 = point3.x - point1.x;
  4162. var y2 = point3.y - point1.y;
  4163. var z2 = point3.z - point1.z;
  4164. var yz = (y1 * z2) - (z1 * y2);
  4165. var xz = (z1 * x2) - (x1 * z2);
  4166. var xy = (x1 * y2) - (y1 * x2);
  4167. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  4168. var invPyth;
  4169. if (pyth !== 0) {
  4170. invPyth = 1.0 / pyth;
  4171. }
  4172. else {
  4173. invPyth = 0.0;
  4174. }
  4175. this.normal.x = yz * invPyth;
  4176. this.normal.y = xz * invPyth;
  4177. this.normal.z = xy * invPyth;
  4178. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  4179. return this;
  4180. };
  4181. /**
  4182. * Boolean : True is the vector "direction" is the same side than the plane normal.
  4183. */
  4184. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  4185. var dot = Vector3.Dot(this.normal, direction);
  4186. return (dot <= epsilon);
  4187. };
  4188. /**
  4189. * Returns the signed distance (float) from the passed point to the Plane.
  4190. */
  4191. Plane.prototype.signedDistanceTo = function (point) {
  4192. return Vector3.Dot(point, this.normal) + this.d;
  4193. };
  4194. // Statics
  4195. /**
  4196. * Returns a new Plane from the passed array.
  4197. */
  4198. Plane.FromArray = function (array) {
  4199. return new Plane(array[0], array[1], array[2], array[3]);
  4200. };
  4201. /**
  4202. * Returns a new Plane defined by the three passed points.
  4203. */
  4204. Plane.FromPoints = function (point1, point2, point3) {
  4205. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  4206. result.copyFromPoints(point1, point2, point3);
  4207. return result;
  4208. };
  4209. /**
  4210. * Returns a new Plane the normal vector to this plane at the passed origin point.
  4211. * Note : the vector "normal" is updated because normalized.
  4212. */
  4213. Plane.FromPositionAndNormal = function (origin, normal) {
  4214. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  4215. normal.normalize();
  4216. result.normal = normal;
  4217. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  4218. return result;
  4219. };
  4220. /**
  4221. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  4222. */
  4223. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  4224. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  4225. return Vector3.Dot(point, normal) + d;
  4226. };
  4227. return Plane;
  4228. }());
  4229. BABYLON.Plane = Plane;
  4230. var Viewport = /** @class */ (function () {
  4231. /**
  4232. * Creates a Viewport object located at (x, y) and sized (width, height).
  4233. */
  4234. function Viewport(x, y, width, height) {
  4235. this.x = x;
  4236. this.y = y;
  4237. this.width = width;
  4238. this.height = height;
  4239. }
  4240. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  4241. if (renderWidthOrEngine.getRenderWidth) {
  4242. var engine = renderWidthOrEngine;
  4243. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  4244. }
  4245. var renderWidth = renderWidthOrEngine;
  4246. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  4247. };
  4248. /**
  4249. * Returns a new Viewport copied from the current one.
  4250. */
  4251. Viewport.prototype.clone = function () {
  4252. return new Viewport(this.x, this.y, this.width, this.height);
  4253. };
  4254. return Viewport;
  4255. }());
  4256. BABYLON.Viewport = Viewport;
  4257. var Frustum = /** @class */ (function () {
  4258. function Frustum() {
  4259. }
  4260. /**
  4261. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  4262. */
  4263. Frustum.GetPlanes = function (transform) {
  4264. var frustumPlanes = [];
  4265. for (var index = 0; index < 6; index++) {
  4266. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  4267. }
  4268. Frustum.GetPlanesToRef(transform, frustumPlanes);
  4269. return frustumPlanes;
  4270. };
  4271. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  4272. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  4273. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  4274. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  4275. frustumPlane.d = transform.m[15] + transform.m[14];
  4276. frustumPlane.normalize();
  4277. };
  4278. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  4279. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  4280. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  4281. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  4282. frustumPlane.d = transform.m[15] - transform.m[14];
  4283. frustumPlane.normalize();
  4284. };
  4285. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  4286. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  4287. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  4288. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  4289. frustumPlane.d = transform.m[15] + transform.m[12];
  4290. frustumPlane.normalize();
  4291. };
  4292. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  4293. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  4294. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  4295. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  4296. frustumPlane.d = transform.m[15] - transform.m[12];
  4297. frustumPlane.normalize();
  4298. };
  4299. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  4300. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  4301. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  4302. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  4303. frustumPlane.d = transform.m[15] - transform.m[13];
  4304. frustumPlane.normalize();
  4305. };
  4306. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  4307. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  4308. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  4309. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  4310. frustumPlane.d = transform.m[15] + transform.m[13];
  4311. frustumPlane.normalize();
  4312. };
  4313. /**
  4314. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  4315. */
  4316. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  4317. // Near
  4318. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  4319. // Far
  4320. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  4321. // Left
  4322. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  4323. // Right
  4324. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  4325. // Top
  4326. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  4327. // Bottom
  4328. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  4329. };
  4330. return Frustum;
  4331. }());
  4332. BABYLON.Frustum = Frustum;
  4333. var Space;
  4334. (function (Space) {
  4335. Space[Space["LOCAL"] = 0] = "LOCAL";
  4336. Space[Space["WORLD"] = 1] = "WORLD";
  4337. Space[Space["BONE"] = 2] = "BONE";
  4338. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  4339. var Axis = /** @class */ (function () {
  4340. function Axis() {
  4341. }
  4342. Axis.X = new Vector3(1.0, 0.0, 0.0);
  4343. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  4344. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  4345. return Axis;
  4346. }());
  4347. BABYLON.Axis = Axis;
  4348. ;
  4349. var BezierCurve = /** @class */ (function () {
  4350. function BezierCurve() {
  4351. }
  4352. /**
  4353. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  4354. */
  4355. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  4356. // Extract X (which is equal to time here)
  4357. var f0 = 1 - 3 * x2 + 3 * x1;
  4358. var f1 = 3 * x2 - 6 * x1;
  4359. var f2 = 3 * x1;
  4360. var refinedT = t;
  4361. for (var i = 0; i < 5; i++) {
  4362. var refinedT2 = refinedT * refinedT;
  4363. var refinedT3 = refinedT2 * refinedT;
  4364. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  4365. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  4366. refinedT -= (x - t) * slope;
  4367. refinedT = Math.min(1, Math.max(0, refinedT));
  4368. }
  4369. // Resolve cubic bezier for the given x
  4370. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  4371. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  4372. Math.pow(refinedT, 3);
  4373. };
  4374. return BezierCurve;
  4375. }());
  4376. BABYLON.BezierCurve = BezierCurve;
  4377. var Orientation;
  4378. (function (Orientation) {
  4379. Orientation[Orientation["CW"] = 0] = "CW";
  4380. Orientation[Orientation["CCW"] = 1] = "CCW";
  4381. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  4382. var Angle = /** @class */ (function () {
  4383. /**
  4384. * Creates an Angle object of "radians" radians (float).
  4385. */
  4386. function Angle(radians) {
  4387. var _this = this;
  4388. /**
  4389. * Returns the Angle value in degrees (float).
  4390. */
  4391. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  4392. /**
  4393. * Returns the Angle value in radians (float).
  4394. */
  4395. this.radians = function () { return _this._radians; };
  4396. this._radians = radians;
  4397. if (this._radians < 0.0)
  4398. this._radians += (2.0 * Math.PI);
  4399. }
  4400. /**
  4401. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  4402. */
  4403. Angle.BetweenTwoPoints = function (a, b) {
  4404. var delta = b.subtract(a);
  4405. var theta = Math.atan2(delta.y, delta.x);
  4406. return new Angle(theta);
  4407. };
  4408. /**
  4409. * Returns a new Angle object from the passed float in radians.
  4410. */
  4411. Angle.FromRadians = function (radians) {
  4412. return new Angle(radians);
  4413. };
  4414. /**
  4415. * Returns a new Angle object from the passed float in degrees.
  4416. */
  4417. Angle.FromDegrees = function (degrees) {
  4418. return new Angle(degrees * Math.PI / 180.0);
  4419. };
  4420. return Angle;
  4421. }());
  4422. BABYLON.Angle = Angle;
  4423. var Arc2 = /** @class */ (function () {
  4424. /**
  4425. * Creates an Arc object from the three passed points : start, middle and end.
  4426. */
  4427. function Arc2(startPoint, midPoint, endPoint) {
  4428. this.startPoint = startPoint;
  4429. this.midPoint = midPoint;
  4430. this.endPoint = endPoint;
  4431. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  4432. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  4433. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  4434. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  4435. 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);
  4436. this.radius = this.centerPoint.subtract(this.startPoint).length();
  4437. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  4438. var a1 = this.startAngle.degrees();
  4439. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  4440. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  4441. // angles correction
  4442. if (a2 - a1 > +180.0)
  4443. a2 -= 360.0;
  4444. if (a2 - a1 < -180.0)
  4445. a2 += 360.0;
  4446. if (a3 - a2 > +180.0)
  4447. a3 -= 360.0;
  4448. if (a3 - a2 < -180.0)
  4449. a3 += 360.0;
  4450. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  4451. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  4452. }
  4453. return Arc2;
  4454. }());
  4455. BABYLON.Arc2 = Arc2;
  4456. var Path2 = /** @class */ (function () {
  4457. /**
  4458. * Creates a Path2 object from the starting 2D coordinates x and y.
  4459. */
  4460. function Path2(x, y) {
  4461. this._points = new Array();
  4462. this._length = 0.0;
  4463. this.closed = false;
  4464. this._points.push(new Vector2(x, y));
  4465. }
  4466. /**
  4467. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  4468. * Returns the updated Path2.
  4469. */
  4470. Path2.prototype.addLineTo = function (x, y) {
  4471. if (this.closed) {
  4472. //Tools.Error("cannot add lines to closed paths");
  4473. return this;
  4474. }
  4475. var newPoint = new Vector2(x, y);
  4476. var previousPoint = this._points[this._points.length - 1];
  4477. this._points.push(newPoint);
  4478. this._length += newPoint.subtract(previousPoint).length();
  4479. return this;
  4480. };
  4481. /**
  4482. * 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.
  4483. * Returns the updated Path2.
  4484. */
  4485. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  4486. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  4487. if (this.closed) {
  4488. //Tools.Error("cannot add arcs to closed paths");
  4489. return this;
  4490. }
  4491. var startPoint = this._points[this._points.length - 1];
  4492. var midPoint = new Vector2(midX, midY);
  4493. var endPoint = new Vector2(endX, endY);
  4494. var arc = new Arc2(startPoint, midPoint, endPoint);
  4495. var increment = arc.angle.radians() / numberOfSegments;
  4496. if (arc.orientation === Orientation.CW)
  4497. increment *= -1;
  4498. var currentAngle = arc.startAngle.radians() + increment;
  4499. for (var i = 0; i < numberOfSegments; i++) {
  4500. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  4501. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  4502. this.addLineTo(x, y);
  4503. currentAngle += increment;
  4504. }
  4505. return this;
  4506. };
  4507. /**
  4508. * Closes the Path2.
  4509. * Returns the Path2.
  4510. */
  4511. Path2.prototype.close = function () {
  4512. this.closed = true;
  4513. return this;
  4514. };
  4515. /**
  4516. * Returns the Path2 total length (float).
  4517. */
  4518. Path2.prototype.length = function () {
  4519. var result = this._length;
  4520. if (!this.closed) {
  4521. var lastPoint = this._points[this._points.length - 1];
  4522. var firstPoint = this._points[0];
  4523. result += (firstPoint.subtract(lastPoint).length());
  4524. }
  4525. return result;
  4526. };
  4527. /**
  4528. * Returns the Path2 internal array of points.
  4529. */
  4530. Path2.prototype.getPoints = function () {
  4531. return this._points;
  4532. };
  4533. /**
  4534. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  4535. */
  4536. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  4537. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  4538. //Tools.Error("normalized length position should be between 0 and 1.");
  4539. return Vector2.Zero();
  4540. }
  4541. var lengthPosition = normalizedLengthPosition * this.length();
  4542. var previousOffset = 0;
  4543. for (var i = 0; i < this._points.length; i++) {
  4544. var j = (i + 1) % this._points.length;
  4545. var a = this._points[i];
  4546. var b = this._points[j];
  4547. var bToA = b.subtract(a);
  4548. var nextOffset = (bToA.length() + previousOffset);
  4549. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  4550. var dir = bToA.normalize();
  4551. var localOffset = lengthPosition - previousOffset;
  4552. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  4553. }
  4554. previousOffset = nextOffset;
  4555. }
  4556. //Tools.Error("internal error");
  4557. return Vector2.Zero();
  4558. };
  4559. /**
  4560. * Returns a new Path2 starting at the coordinates (x, y).
  4561. */
  4562. Path2.StartingAt = function (x, y) {
  4563. return new Path2(x, y);
  4564. };
  4565. return Path2;
  4566. }());
  4567. BABYLON.Path2 = Path2;
  4568. var Path3D = /** @class */ (function () {
  4569. /**
  4570. * new Path3D(path, normal, raw)
  4571. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  4572. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  4573. * path : an array of Vector3, the curve axis of the Path3D
  4574. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  4575. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  4576. */
  4577. function Path3D(path, firstNormal, raw) {
  4578. if (firstNormal === void 0) { firstNormal = null; }
  4579. this.path = path;
  4580. this._curve = new Array();
  4581. this._distances = new Array();
  4582. this._tangents = new Array();
  4583. this._normals = new Array();
  4584. this._binormals = new Array();
  4585. for (var p = 0; p < path.length; p++) {
  4586. this._curve[p] = path[p].clone(); // hard copy
  4587. }
  4588. this._raw = raw || false;
  4589. this._compute(firstNormal);
  4590. }
  4591. /**
  4592. * Returns the Path3D array of successive Vector3 designing its curve.
  4593. */
  4594. Path3D.prototype.getCurve = function () {
  4595. return this._curve;
  4596. };
  4597. /**
  4598. * Returns an array populated with tangent vectors on each Path3D curve point.
  4599. */
  4600. Path3D.prototype.getTangents = function () {
  4601. return this._tangents;
  4602. };
  4603. /**
  4604. * Returns an array populated with normal vectors on each Path3D curve point.
  4605. */
  4606. Path3D.prototype.getNormals = function () {
  4607. return this._normals;
  4608. };
  4609. /**
  4610. * Returns an array populated with binormal vectors on each Path3D curve point.
  4611. */
  4612. Path3D.prototype.getBinormals = function () {
  4613. return this._binormals;
  4614. };
  4615. /**
  4616. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  4617. */
  4618. Path3D.prototype.getDistances = function () {
  4619. return this._distances;
  4620. };
  4621. /**
  4622. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  4623. * Returns the same object updated.
  4624. */
  4625. Path3D.prototype.update = function (path, firstNormal) {
  4626. if (firstNormal === void 0) { firstNormal = null; }
  4627. for (var p = 0; p < path.length; p++) {
  4628. this._curve[p].x = path[p].x;
  4629. this._curve[p].y = path[p].y;
  4630. this._curve[p].z = path[p].z;
  4631. }
  4632. this._compute(firstNormal);
  4633. return this;
  4634. };
  4635. // private function compute() : computes tangents, normals and binormals
  4636. Path3D.prototype._compute = function (firstNormal) {
  4637. var l = this._curve.length;
  4638. // first and last tangents
  4639. this._tangents[0] = this._getFirstNonNullVector(0);
  4640. if (!this._raw) {
  4641. this._tangents[0].normalize();
  4642. }
  4643. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  4644. if (!this._raw) {
  4645. this._tangents[l - 1].normalize();
  4646. }
  4647. // normals and binormals at first point : arbitrary vector with _normalVector()
  4648. var tg0 = this._tangents[0];
  4649. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  4650. this._normals[0] = pp0;
  4651. if (!this._raw) {
  4652. this._normals[0].normalize();
  4653. }
  4654. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  4655. if (!this._raw) {
  4656. this._binormals[0].normalize();
  4657. }
  4658. this._distances[0] = 0.0;
  4659. // normals and binormals : next points
  4660. var prev; // previous vector (segment)
  4661. var cur; // current vector (segment)
  4662. var curTang; // current tangent
  4663. // previous normal
  4664. var prevBinor; // previous binormal
  4665. for (var i = 1; i < l; i++) {
  4666. // tangents
  4667. prev = this._getLastNonNullVector(i);
  4668. if (i < l - 1) {
  4669. cur = this._getFirstNonNullVector(i);
  4670. this._tangents[i] = prev.add(cur);
  4671. this._tangents[i].normalize();
  4672. }
  4673. this._distances[i] = this._distances[i - 1] + prev.length();
  4674. // normals and binormals
  4675. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  4676. curTang = this._tangents[i];
  4677. prevBinor = this._binormals[i - 1];
  4678. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  4679. if (!this._raw) {
  4680. this._normals[i].normalize();
  4681. }
  4682. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  4683. if (!this._raw) {
  4684. this._binormals[i].normalize();
  4685. }
  4686. }
  4687. };
  4688. // private function getFirstNonNullVector(index)
  4689. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  4690. Path3D.prototype._getFirstNonNullVector = function (index) {
  4691. var i = 1;
  4692. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  4693. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  4694. i++;
  4695. nNVector = this._curve[index + i].subtract(this._curve[index]);
  4696. }
  4697. return nNVector;
  4698. };
  4699. // private function getLastNonNullVector(index)
  4700. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  4701. Path3D.prototype._getLastNonNullVector = function (index) {
  4702. var i = 1;
  4703. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  4704. while (nLVector.length() === 0 && index > i + 1) {
  4705. i++;
  4706. nLVector = this._curve[index].subtract(this._curve[index - i]);
  4707. }
  4708. return nLVector;
  4709. };
  4710. // private function normalVector(v0, vt, va) :
  4711. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  4712. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  4713. Path3D.prototype._normalVector = function (v0, vt, va) {
  4714. var normal0;
  4715. var tgl = vt.length();
  4716. if (tgl === 0.0) {
  4717. tgl = 1.0;
  4718. }
  4719. if (va === undefined || va === null) {
  4720. var point;
  4721. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  4722. point = new Vector3(0.0, -1.0, 0.0);
  4723. }
  4724. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  4725. point = new Vector3(1.0, 0.0, 0.0);
  4726. }
  4727. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  4728. point = new Vector3(0.0, 0.0, 1.0);
  4729. }
  4730. else {
  4731. point = Vector3.Zero();
  4732. }
  4733. normal0 = Vector3.Cross(vt, point);
  4734. }
  4735. else {
  4736. normal0 = Vector3.Cross(vt, va);
  4737. Vector3.CrossToRef(normal0, vt, normal0);
  4738. }
  4739. normal0.normalize();
  4740. return normal0;
  4741. };
  4742. return Path3D;
  4743. }());
  4744. BABYLON.Path3D = Path3D;
  4745. var Curve3 = /** @class */ (function () {
  4746. /**
  4747. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  4748. * A Curve3 is designed from a series of successive Vector3.
  4749. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  4750. */
  4751. function Curve3(points) {
  4752. this._length = 0.0;
  4753. this._points = points;
  4754. this._length = this._computeLength(points);
  4755. }
  4756. /**
  4757. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  4758. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  4759. * @param v1 (Vector3) the control point
  4760. * @param v2 (Vector3) the end point of the Quadratic Bezier
  4761. * @param nbPoints (integer) the wanted number of points in the curve
  4762. */
  4763. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  4764. nbPoints = nbPoints > 2 ? nbPoints : 3;
  4765. var bez = new Array();
  4766. var equation = function (t, val0, val1, val2) {
  4767. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  4768. return res;
  4769. };
  4770. for (var i = 0; i <= nbPoints; i++) {
  4771. 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)));
  4772. }
  4773. return new Curve3(bez);
  4774. };
  4775. /**
  4776. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  4777. * @param v0 (Vector3) the origin point of the Cubic Bezier
  4778. * @param v1 (Vector3) the first control point
  4779. * @param v2 (Vector3) the second control point
  4780. * @param v3 (Vector3) the end point of the Cubic Bezier
  4781. * @param nbPoints (integer) the wanted number of points in the curve
  4782. */
  4783. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  4784. nbPoints = nbPoints > 3 ? nbPoints : 4;
  4785. var bez = new Array();
  4786. var equation = function (t, val0, val1, val2, val3) {
  4787. 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;
  4788. return res;
  4789. };
  4790. for (var i = 0; i <= nbPoints; i++) {
  4791. 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)));
  4792. }
  4793. return new Curve3(bez);
  4794. };
  4795. /**
  4796. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  4797. * @param p1 (Vector3) the origin point of the Hermite Spline
  4798. * @param t1 (Vector3) the tangent vector at the origin point
  4799. * @param p2 (Vector3) the end point of the Hermite Spline
  4800. * @param t2 (Vector3) the tangent vector at the end point
  4801. * @param nbPoints (integer) the wanted number of points in the curve
  4802. */
  4803. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  4804. var hermite = new Array();
  4805. var step = 1.0 / nbPoints;
  4806. for (var i = 0; i <= nbPoints; i++) {
  4807. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  4808. }
  4809. return new Curve3(hermite);
  4810. };
  4811. /**
  4812. * Returns a Curve3 object along a CatmullRom Spline curve :
  4813. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  4814. * @param nbPoints (integer) the wanted number of points between each curve control points.
  4815. */
  4816. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  4817. var totalPoints = new Array();
  4818. totalPoints.push(points[0].clone());
  4819. Array.prototype.push.apply(totalPoints, points);
  4820. totalPoints.push(points[points.length - 1].clone());
  4821. var catmullRom = new Array();
  4822. var step = 1.0 / nbPoints;
  4823. var amount = 0.0;
  4824. for (var i = 0; i < totalPoints.length - 3; i++) {
  4825. amount = 0;
  4826. for (var c = 0; c < nbPoints; c++) {
  4827. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  4828. amount += step;
  4829. }
  4830. }
  4831. i--;
  4832. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  4833. return new Curve3(catmullRom);
  4834. };
  4835. /**
  4836. * Returns the Curve3 stored array of successive Vector3
  4837. */
  4838. Curve3.prototype.getPoints = function () {
  4839. return this._points;
  4840. };
  4841. /**
  4842. * Returns the computed length (float) of the curve.
  4843. */
  4844. Curve3.prototype.length = function () {
  4845. return this._length;
  4846. };
  4847. /**
  4848. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  4849. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  4850. * curveA and curveB keep unchanged.
  4851. */
  4852. Curve3.prototype.continue = function (curve) {
  4853. var lastPoint = this._points[this._points.length - 1];
  4854. var continuedPoints = this._points.slice();
  4855. var curvePoints = curve.getPoints();
  4856. for (var i = 1; i < curvePoints.length; i++) {
  4857. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  4858. }
  4859. var continuedCurve = new Curve3(continuedPoints);
  4860. return continuedCurve;
  4861. };
  4862. Curve3.prototype._computeLength = function (path) {
  4863. var l = 0;
  4864. for (var i = 1; i < path.length; i++) {
  4865. l += (path[i].subtract(path[i - 1])).length();
  4866. }
  4867. return l;
  4868. };
  4869. return Curve3;
  4870. }());
  4871. BABYLON.Curve3 = Curve3;
  4872. // Vertex formats
  4873. var PositionNormalVertex = /** @class */ (function () {
  4874. function PositionNormalVertex(position, normal) {
  4875. if (position === void 0) { position = Vector3.Zero(); }
  4876. if (normal === void 0) { normal = Vector3.Up(); }
  4877. this.position = position;
  4878. this.normal = normal;
  4879. }
  4880. PositionNormalVertex.prototype.clone = function () {
  4881. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  4882. };
  4883. return PositionNormalVertex;
  4884. }());
  4885. BABYLON.PositionNormalVertex = PositionNormalVertex;
  4886. var PositionNormalTextureVertex = /** @class */ (function () {
  4887. function PositionNormalTextureVertex(position, normal, uv) {
  4888. if (position === void 0) { position = Vector3.Zero(); }
  4889. if (normal === void 0) { normal = Vector3.Up(); }
  4890. if (uv === void 0) { uv = Vector2.Zero(); }
  4891. this.position = position;
  4892. this.normal = normal;
  4893. this.uv = uv;
  4894. }
  4895. PositionNormalTextureVertex.prototype.clone = function () {
  4896. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  4897. };
  4898. return PositionNormalTextureVertex;
  4899. }());
  4900. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  4901. // Temporary pre-allocated objects for engine internal use
  4902. // usage in any internal function :
  4903. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  4904. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  4905. var Tmp = /** @class */ (function () {
  4906. function Tmp() {
  4907. }
  4908. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  4909. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  4910. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  4911. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  4912. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  4913. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  4914. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  4915. Matrix.Zero(), Matrix.Zero(),
  4916. Matrix.Zero(), Matrix.Zero(),
  4917. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  4918. return Tmp;
  4919. }());
  4920. BABYLON.Tmp = Tmp;
  4921. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  4922. var MathTmp = /** @class */ (function () {
  4923. function MathTmp() {
  4924. }
  4925. MathTmp.Vector3 = [Vector3.Zero()];
  4926. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  4927. MathTmp.Quaternion = [Quaternion.Zero()];
  4928. return MathTmp;
  4929. }());
  4930. })(BABYLON || (BABYLON = {}));
  4931. //# sourceMappingURL=babylon.math.js.map
  4932. var BABYLON;
  4933. (function (BABYLON) {
  4934. var Scalar = /** @class */ (function () {
  4935. function Scalar() {
  4936. }
  4937. /**
  4938. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  4939. */
  4940. Scalar.WithinEpsilon = function (a, b, epsilon) {
  4941. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  4942. var num = a - b;
  4943. return -epsilon <= num && num <= epsilon;
  4944. };
  4945. /**
  4946. * Returns a string : the upper case translation of the number i to hexadecimal.
  4947. */
  4948. Scalar.ToHex = function (i) {
  4949. var str = i.toString(16);
  4950. if (i <= 15) {
  4951. return ("0" + str).toUpperCase();
  4952. }
  4953. return str.toUpperCase();
  4954. };
  4955. /**
  4956. * Returns -1 if value is negative and +1 is value is positive.
  4957. * Returns the value itself if it's equal to zero.
  4958. */
  4959. Scalar.Sign = function (value) {
  4960. value = +value; // convert to a number
  4961. if (value === 0 || isNaN(value))
  4962. return value;
  4963. return value > 0 ? 1 : -1;
  4964. };
  4965. /**
  4966. * Returns the value itself if it's between min and max.
  4967. * Returns min if the value is lower than min.
  4968. * Returns max if the value is greater than max.
  4969. */
  4970. Scalar.Clamp = function (value, min, max) {
  4971. if (min === void 0) { min = 0; }
  4972. if (max === void 0) { max = 1; }
  4973. return Math.min(max, Math.max(min, value));
  4974. };
  4975. /**
  4976. * Returns the log2 of value.
  4977. */
  4978. Scalar.Log2 = function (value) {
  4979. return Math.log(value) * Math.LOG2E;
  4980. };
  4981. /**
  4982. * Loops the value, so that it is never larger than length and never smaller than 0.
  4983. *
  4984. * This is similar to the modulo operator but it works with floating point numbers.
  4985. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  4986. * With t = 5 and length = 2.5, the result would be 0.0.
  4987. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  4988. */
  4989. Scalar.Repeat = function (value, length) {
  4990. return value - Math.floor(value / length) * length;
  4991. };
  4992. /**
  4993. * Normalize the value between 0.0 and 1.0 using min and max values
  4994. */
  4995. Scalar.Normalize = function (value, min, max) {
  4996. return (value - min) / (max - min);
  4997. };
  4998. /**
  4999. * Denormalize the value from 0.0 and 1.0 using min and max values
  5000. */
  5001. Scalar.Denormalize = function (normalized, min, max) {
  5002. return (normalized * (max - min) + min);
  5003. };
  5004. /**
  5005. * Calculates the shortest difference between two given angles given in degrees.
  5006. */
  5007. Scalar.DeltaAngle = function (current, target) {
  5008. var num = Scalar.Repeat(target - current, 360.0);
  5009. if (num > 180.0) {
  5010. num -= 360.0;
  5011. }
  5012. return num;
  5013. };
  5014. /**
  5015. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  5016. *
  5017. * The returned value will move back and forth between 0 and length
  5018. */
  5019. Scalar.PingPong = function (tx, length) {
  5020. var t = Scalar.Repeat(tx, length * 2.0);
  5021. return length - Math.abs(t - length);
  5022. };
  5023. /**
  5024. * Interpolates between min and max with smoothing at the limits.
  5025. *
  5026. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  5027. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  5028. */
  5029. Scalar.SmoothStep = function (from, to, tx) {
  5030. var t = Scalar.Clamp(tx);
  5031. t = -2.0 * t * t * t + 3.0 * t * t;
  5032. return to * t + from * (1.0 - t);
  5033. };
  5034. /**
  5035. * Moves a value current towards target.
  5036. *
  5037. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  5038. * Negative values of maxDelta pushes the value away from target.
  5039. */
  5040. Scalar.MoveTowards = function (current, target, maxDelta) {
  5041. var result = 0;
  5042. if (Math.abs(target - current) <= maxDelta) {
  5043. result = target;
  5044. }
  5045. else {
  5046. result = current + Scalar.Sign(target - current) * maxDelta;
  5047. }
  5048. return result;
  5049. };
  5050. /**
  5051. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  5052. *
  5053. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  5054. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  5055. */
  5056. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  5057. var num = Scalar.DeltaAngle(current, target);
  5058. var result = 0;
  5059. if (-maxDelta < num && num < maxDelta) {
  5060. result = target;
  5061. }
  5062. else {
  5063. target = current + num;
  5064. result = Scalar.MoveTowards(current, target, maxDelta);
  5065. }
  5066. return result;
  5067. };
  5068. /**
  5069. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  5070. */
  5071. Scalar.Lerp = function (start, end, amount) {
  5072. return start + ((end - start) * amount);
  5073. };
  5074. /**
  5075. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  5076. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  5077. */
  5078. Scalar.LerpAngle = function (start, end, amount) {
  5079. var num = Scalar.Repeat(end - start, 360.0);
  5080. if (num > 180.0) {
  5081. num -= 360.0;
  5082. }
  5083. return start + num * Scalar.Clamp(amount);
  5084. };
  5085. /**
  5086. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  5087. */
  5088. Scalar.InverseLerp = function (a, b, value) {
  5089. var result = 0;
  5090. if (a != b) {
  5091. result = Scalar.Clamp((value - a) / (b - a));
  5092. }
  5093. else {
  5094. result = 0.0;
  5095. }
  5096. return result;
  5097. };
  5098. /**
  5099. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  5100. */
  5101. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  5102. var squared = amount * amount;
  5103. var cubed = amount * squared;
  5104. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  5105. var part2 = (-2.0 * cubed) + (3.0 * squared);
  5106. var part3 = (cubed - (2.0 * squared)) + amount;
  5107. var part4 = cubed - squared;
  5108. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  5109. };
  5110. /**
  5111. * Returns a random float number between and min and max values
  5112. */
  5113. Scalar.RandomRange = function (min, max) {
  5114. if (min === max)
  5115. return min;
  5116. return ((Math.random() * (max - min)) + min);
  5117. };
  5118. /**
  5119. * This function returns percentage of a number in a given range.
  5120. *
  5121. * RangeToPercent(40,20,60) will return 0.5 (50%)
  5122. * RangeToPercent(34,0,100) will return 0.34 (34%)
  5123. */
  5124. Scalar.RangeToPercent = function (number, min, max) {
  5125. return ((number - min) / (max - min));
  5126. };
  5127. /**
  5128. * This function returns number that corresponds to the percentage in a given range.
  5129. *
  5130. * PercentToRange(0.34,0,100) will return 34.
  5131. */
  5132. Scalar.PercentToRange = function (percent, min, max) {
  5133. return ((max - min) * percent + min);
  5134. };
  5135. /**
  5136. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  5137. * @param angle The angle to normalize in radian.
  5138. * @return The converted angle.
  5139. */
  5140. Scalar.NormalizeRadians = function (angle) {
  5141. // More precise but slower version kept for reference.
  5142. // angle = angle % Tools.TwoPi;
  5143. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  5144. //if (angle > Math.PI) {
  5145. // angle -= Tools.TwoPi;
  5146. //}
  5147. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  5148. return angle;
  5149. };
  5150. /**
  5151. * Two pi constants convenient for computation.
  5152. */
  5153. Scalar.TwoPi = Math.PI * 2;
  5154. return Scalar;
  5155. }());
  5156. BABYLON.Scalar = Scalar;
  5157. })(BABYLON || (BABYLON = {}));
  5158. //# sourceMappingURL=babylon.math.scalar.js.map
  5159. //# sourceMappingURL=babylon.mixins.js.map
  5160. var BABYLON;
  5161. (function (BABYLON) {
  5162. var __decoratorInitialStore = {};
  5163. var __mergedStore = {};
  5164. var _copySource = function (creationFunction, source, instanciate) {
  5165. var destination = creationFunction();
  5166. // Tags
  5167. if (BABYLON.Tags) {
  5168. BABYLON.Tags.AddTagsTo(destination, source.tags);
  5169. }
  5170. var classStore = getMergedStore(destination);
  5171. // Properties
  5172. for (var property in classStore) {
  5173. var propertyDescriptor = classStore[property];
  5174. var sourceProperty = source[property];
  5175. var propertyType = propertyDescriptor.type;
  5176. if (sourceProperty !== undefined && sourceProperty !== null) {
  5177. switch (propertyType) {
  5178. case 0: // Value
  5179. case 6:// Mesh reference
  5180. destination[property] = sourceProperty;
  5181. break;
  5182. case 1:// Texture
  5183. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  5184. break;
  5185. case 2: // Color3
  5186. case 3: // FresnelParameters
  5187. case 4: // Vector2
  5188. case 5: // Vector3
  5189. case 7: // Color Curves
  5190. case 10:// Quaternion
  5191. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  5192. break;
  5193. }
  5194. }
  5195. }
  5196. return destination;
  5197. };
  5198. function getDirectStore(target) {
  5199. var classKey = target.getClassName();
  5200. if (!__decoratorInitialStore[classKey]) {
  5201. __decoratorInitialStore[classKey] = {};
  5202. }
  5203. return __decoratorInitialStore[classKey];
  5204. }
  5205. /**
  5206. * Return the list of properties flagged as serializable
  5207. * @param target: host object
  5208. */
  5209. function getMergedStore(target) {
  5210. var classKey = target.getClassName();
  5211. if (__mergedStore[classKey]) {
  5212. return __mergedStore[classKey];
  5213. }
  5214. __mergedStore[classKey] = {};
  5215. var store = __mergedStore[classKey];
  5216. var currentTarget = target;
  5217. var currentKey = classKey;
  5218. while (currentKey) {
  5219. var initialStore = __decoratorInitialStore[currentKey];
  5220. for (var property in initialStore) {
  5221. store[property] = initialStore[property];
  5222. }
  5223. var parent_1 = void 0;
  5224. var done = false;
  5225. do {
  5226. parent_1 = Object.getPrototypeOf(currentTarget);
  5227. if (!parent_1.getClassName) {
  5228. done = true;
  5229. break;
  5230. }
  5231. if (parent_1.getClassName() !== currentKey) {
  5232. break;
  5233. }
  5234. currentTarget = parent_1;
  5235. } while (parent_1);
  5236. if (done) {
  5237. break;
  5238. }
  5239. currentKey = parent_1.getClassName();
  5240. currentTarget = parent_1;
  5241. }
  5242. return store;
  5243. }
  5244. function generateSerializableMember(type, sourceName) {
  5245. return function (target, propertyKey) {
  5246. var classStore = getDirectStore(target);
  5247. if (!classStore[propertyKey]) {
  5248. classStore[propertyKey] = { type: type, sourceName: sourceName };
  5249. }
  5250. };
  5251. }
  5252. function generateExpandMember(setCallback, targetKey) {
  5253. if (targetKey === void 0) { targetKey = null; }
  5254. return function (target, propertyKey) {
  5255. var key = targetKey || ("_" + propertyKey);
  5256. Object.defineProperty(target, propertyKey, {
  5257. get: function () {
  5258. return this[key];
  5259. },
  5260. set: function (value) {
  5261. if (this[key] === value) {
  5262. return;
  5263. }
  5264. this[key] = value;
  5265. target[setCallback].apply(this);
  5266. },
  5267. enumerable: true,
  5268. configurable: true
  5269. });
  5270. };
  5271. }
  5272. function expandToProperty(callback, targetKey) {
  5273. if (targetKey === void 0) { targetKey = null; }
  5274. return generateExpandMember(callback, targetKey);
  5275. }
  5276. BABYLON.expandToProperty = expandToProperty;
  5277. function serialize(sourceName) {
  5278. return generateSerializableMember(0, sourceName); // value member
  5279. }
  5280. BABYLON.serialize = serialize;
  5281. function serializeAsTexture(sourceName) {
  5282. return generateSerializableMember(1, sourceName); // texture member
  5283. }
  5284. BABYLON.serializeAsTexture = serializeAsTexture;
  5285. function serializeAsColor3(sourceName) {
  5286. return generateSerializableMember(2, sourceName); // color3 member
  5287. }
  5288. BABYLON.serializeAsColor3 = serializeAsColor3;
  5289. function serializeAsFresnelParameters(sourceName) {
  5290. return generateSerializableMember(3, sourceName); // fresnel parameters member
  5291. }
  5292. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  5293. function serializeAsVector2(sourceName) {
  5294. return generateSerializableMember(4, sourceName); // vector2 member
  5295. }
  5296. BABYLON.serializeAsVector2 = serializeAsVector2;
  5297. function serializeAsVector3(sourceName) {
  5298. return generateSerializableMember(5, sourceName); // vector3 member
  5299. }
  5300. BABYLON.serializeAsVector3 = serializeAsVector3;
  5301. function serializeAsMeshReference(sourceName) {
  5302. return generateSerializableMember(6, sourceName); // mesh reference member
  5303. }
  5304. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  5305. function serializeAsColorCurves(sourceName) {
  5306. return generateSerializableMember(7, sourceName); // color curves
  5307. }
  5308. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  5309. function serializeAsColor4(sourceName) {
  5310. return generateSerializableMember(8, sourceName); // color 4
  5311. }
  5312. BABYLON.serializeAsColor4 = serializeAsColor4;
  5313. function serializeAsImageProcessingConfiguration(sourceName) {
  5314. return generateSerializableMember(9, sourceName); // image processing
  5315. }
  5316. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  5317. function serializeAsQuaternion(sourceName) {
  5318. return generateSerializableMember(10, sourceName); // quaternion member
  5319. }
  5320. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  5321. var SerializationHelper = /** @class */ (function () {
  5322. function SerializationHelper() {
  5323. }
  5324. SerializationHelper.Serialize = function (entity, serializationObject) {
  5325. if (!serializationObject) {
  5326. serializationObject = {};
  5327. }
  5328. // Tags
  5329. if (BABYLON.Tags) {
  5330. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  5331. }
  5332. var serializedProperties = getMergedStore(entity);
  5333. // Properties
  5334. for (var property in serializedProperties) {
  5335. var propertyDescriptor = serializedProperties[property];
  5336. var targetPropertyName = propertyDescriptor.sourceName || property;
  5337. var propertyType = propertyDescriptor.type;
  5338. var sourceProperty = entity[property];
  5339. if (sourceProperty !== undefined && sourceProperty !== null) {
  5340. switch (propertyType) {
  5341. case 0:// Value
  5342. serializationObject[targetPropertyName] = sourceProperty;
  5343. break;
  5344. case 1:// Texture
  5345. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5346. break;
  5347. case 2:// Color3
  5348. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5349. break;
  5350. case 3:// FresnelParameters
  5351. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5352. break;
  5353. case 4:// Vector2
  5354. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5355. break;
  5356. case 5:// Vector3
  5357. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5358. break;
  5359. case 6:// Mesh reference
  5360. serializationObject[targetPropertyName] = sourceProperty.id;
  5361. break;
  5362. case 7:// Color Curves
  5363. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5364. break;
  5365. case 8:// Color 4
  5366. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5367. break;
  5368. case 9:// Image Processing
  5369. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5370. break;
  5371. }
  5372. }
  5373. }
  5374. return serializationObject;
  5375. };
  5376. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  5377. if (rootUrl === void 0) { rootUrl = null; }
  5378. var destination = creationFunction();
  5379. if (!rootUrl) {
  5380. rootUrl = "";
  5381. }
  5382. // Tags
  5383. if (BABYLON.Tags) {
  5384. BABYLON.Tags.AddTagsTo(destination, source.tags);
  5385. }
  5386. var classStore = getMergedStore(destination);
  5387. // Properties
  5388. for (var property in classStore) {
  5389. var propertyDescriptor = classStore[property];
  5390. var sourceProperty = source[propertyDescriptor.sourceName || property];
  5391. var propertyType = propertyDescriptor.type;
  5392. if (sourceProperty !== undefined && sourceProperty !== null) {
  5393. var dest = destination;
  5394. switch (propertyType) {
  5395. case 0:// Value
  5396. dest[property] = sourceProperty;
  5397. break;
  5398. case 1:// Texture
  5399. if (scene) {
  5400. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  5401. }
  5402. break;
  5403. case 2:// Color3
  5404. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  5405. break;
  5406. case 3:// FresnelParameters
  5407. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  5408. break;
  5409. case 4:// Vector2
  5410. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  5411. break;
  5412. case 5:// Vector3
  5413. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  5414. break;
  5415. case 6:// Mesh reference
  5416. if (scene) {
  5417. dest[property] = scene.getLastMeshByID(sourceProperty);
  5418. }
  5419. break;
  5420. case 7:// Color Curves
  5421. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  5422. break;
  5423. case 8:// Color 4
  5424. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  5425. break;
  5426. case 9:// Image Processing
  5427. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  5428. break;
  5429. }
  5430. }
  5431. }
  5432. return destination;
  5433. };
  5434. SerializationHelper.Clone = function (creationFunction, source) {
  5435. return _copySource(creationFunction, source, false);
  5436. };
  5437. SerializationHelper.Instanciate = function (creationFunction, source) {
  5438. return _copySource(creationFunction, source, true);
  5439. };
  5440. return SerializationHelper;
  5441. }());
  5442. BABYLON.SerializationHelper = SerializationHelper;
  5443. })(BABYLON || (BABYLON = {}));
  5444. //# sourceMappingURL=babylon.decorators.js.map
  5445. var BABYLON;
  5446. (function (BABYLON) {
  5447. /**
  5448. * A class serves as a medium between the observable and its observers
  5449. */
  5450. var EventState = /** @class */ (function () {
  5451. /**
  5452. * If the callback of a given Observer set skipNextObservers to true the following observers will be ignored
  5453. */
  5454. function EventState(mask, skipNextObservers, target, currentTarget) {
  5455. if (skipNextObservers === void 0) { skipNextObservers = false; }
  5456. this.initalize(mask, skipNextObservers, target, currentTarget);
  5457. }
  5458. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  5459. if (skipNextObservers === void 0) { skipNextObservers = false; }
  5460. this.mask = mask;
  5461. this.skipNextObservers = skipNextObservers;
  5462. this.target = target;
  5463. this.currentTarget = currentTarget;
  5464. return this;
  5465. };
  5466. return EventState;
  5467. }());
  5468. BABYLON.EventState = EventState;
  5469. /**
  5470. * Represent an Observer registered to a given Observable object.
  5471. */
  5472. var Observer = /** @class */ (function () {
  5473. function Observer(callback, mask, scope) {
  5474. if (scope === void 0) { scope = null; }
  5475. this.callback = callback;
  5476. this.mask = mask;
  5477. this.scope = scope;
  5478. }
  5479. return Observer;
  5480. }());
  5481. BABYLON.Observer = Observer;
  5482. /**
  5483. * Represent a list of observers registered to multiple Observables object.
  5484. */
  5485. var MultiObserver = /** @class */ (function () {
  5486. function MultiObserver() {
  5487. }
  5488. MultiObserver.prototype.dispose = function () {
  5489. if (this._observers && this._observables) {
  5490. for (var index = 0; index < this._observers.length; index++) {
  5491. this._observables[index].remove(this._observers[index]);
  5492. }
  5493. }
  5494. this._observers = null;
  5495. this._observables = null;
  5496. };
  5497. MultiObserver.Watch = function (observables, callback, mask, scope) {
  5498. if (mask === void 0) { mask = -1; }
  5499. if (scope === void 0) { scope = null; }
  5500. var result = new MultiObserver();
  5501. result._observers = new Array();
  5502. result._observables = observables;
  5503. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  5504. var observable = observables_1[_i];
  5505. var observer = observable.add(callback, mask, false, scope);
  5506. if (observer) {
  5507. result._observers.push(observer);
  5508. }
  5509. }
  5510. return result;
  5511. };
  5512. return MultiObserver;
  5513. }());
  5514. BABYLON.MultiObserver = MultiObserver;
  5515. /**
  5516. * The Observable class is a simple implementation of the Observable pattern.
  5517. * 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.
  5518. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  5519. * 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).
  5520. * 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.
  5521. */
  5522. var Observable = /** @class */ (function () {
  5523. function Observable(onObserverAdded) {
  5524. this._observers = new Array();
  5525. this._eventState = new EventState(0);
  5526. if (onObserverAdded) {
  5527. this._onObserverAdded = onObserverAdded;
  5528. }
  5529. }
  5530. /**
  5531. * Create a new Observer with the specified callback
  5532. * @param callback the callback that will be executed for that Observer
  5533. * @param mask the mask used to filter observers
  5534. * @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.
  5535. * @param scope optional scope for the callback to be called from
  5536. */
  5537. Observable.prototype.add = function (callback, mask, insertFirst, scope) {
  5538. if (mask === void 0) { mask = -1; }
  5539. if (insertFirst === void 0) { insertFirst = false; }
  5540. if (scope === void 0) { scope = null; }
  5541. if (!callback) {
  5542. return null;
  5543. }
  5544. var observer = new Observer(callback, mask, scope);
  5545. if (insertFirst) {
  5546. this._observers.unshift(observer);
  5547. }
  5548. else {
  5549. this._observers.push(observer);
  5550. }
  5551. if (this._onObserverAdded) {
  5552. this._onObserverAdded(observer);
  5553. }
  5554. return observer;
  5555. };
  5556. /**
  5557. * Remove an Observer from the Observable object
  5558. * @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
  5559. */
  5560. Observable.prototype.remove = function (observer) {
  5561. if (!observer) {
  5562. return false;
  5563. }
  5564. var index = this._observers.indexOf(observer);
  5565. if (index !== -1) {
  5566. this._observers.splice(index, 1);
  5567. return true;
  5568. }
  5569. return false;
  5570. };
  5571. /**
  5572. * Remove a callback from the Observable object
  5573. * @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
  5574. */
  5575. Observable.prototype.removeCallback = function (callback) {
  5576. for (var index = 0; index < this._observers.length; index++) {
  5577. if (this._observers[index].callback === callback) {
  5578. this._observers.splice(index, 1);
  5579. return true;
  5580. }
  5581. }
  5582. return false;
  5583. };
  5584. /**
  5585. * Notify all Observers by calling their respective callback with the given data
  5586. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  5587. * @param eventData
  5588. * @param mask
  5589. */
  5590. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  5591. if (mask === void 0) { mask = -1; }
  5592. if (!this._observers.length) {
  5593. return true;
  5594. }
  5595. var state = this._eventState;
  5596. state.mask = mask;
  5597. state.target = target;
  5598. state.currentTarget = currentTarget;
  5599. state.skipNextObservers = false;
  5600. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  5601. var obs = _a[_i];
  5602. if (obs.mask & mask) {
  5603. if (obs.scope) {
  5604. obs.callback.apply(obs.scope, [eventData, state]);
  5605. }
  5606. else {
  5607. obs.callback(eventData, state);
  5608. }
  5609. }
  5610. if (state.skipNextObservers) {
  5611. return false;
  5612. }
  5613. }
  5614. return true;
  5615. };
  5616. /**
  5617. * Notify a specific observer
  5618. * @param eventData
  5619. * @param mask
  5620. */
  5621. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  5622. if (mask === void 0) { mask = -1; }
  5623. var state = this._eventState;
  5624. state.mask = mask;
  5625. state.skipNextObservers = false;
  5626. observer.callback(eventData, state);
  5627. };
  5628. /**
  5629. * return true is the Observable has at least one Observer registered
  5630. */
  5631. Observable.prototype.hasObservers = function () {
  5632. return this._observers.length > 0;
  5633. };
  5634. /**
  5635. * Clear the list of observers
  5636. */
  5637. Observable.prototype.clear = function () {
  5638. this._observers = new Array();
  5639. this._onObserverAdded = null;
  5640. };
  5641. /**
  5642. * Clone the current observable
  5643. */
  5644. Observable.prototype.clone = function () {
  5645. var result = new Observable();
  5646. result._observers = this._observers.slice(0);
  5647. return result;
  5648. };
  5649. /**
  5650. * Does this observable handles observer registered with a given mask
  5651. * @param {number} trigger - the mask to be tested
  5652. * @return {boolean} whether or not one observer registered with the given mask is handeled
  5653. **/
  5654. Observable.prototype.hasSpecificMask = function (mask) {
  5655. if (mask === void 0) { mask = -1; }
  5656. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  5657. var obs = _a[_i];
  5658. if (obs.mask & mask || obs.mask === mask) {
  5659. return true;
  5660. }
  5661. }
  5662. return false;
  5663. };
  5664. return Observable;
  5665. }());
  5666. BABYLON.Observable = Observable;
  5667. })(BABYLON || (BABYLON = {}));
  5668. //# sourceMappingURL=babylon.observable.js.map
  5669. var BABYLON;
  5670. (function (BABYLON) {
  5671. var SmartArray = /** @class */ (function () {
  5672. function SmartArray(capacity) {
  5673. this.length = 0;
  5674. this.data = new Array(capacity);
  5675. this._id = SmartArray._GlobalId++;
  5676. }
  5677. SmartArray.prototype.push = function (value) {
  5678. this.data[this.length++] = value;
  5679. if (this.length > this.data.length) {
  5680. this.data.length *= 2;
  5681. }
  5682. };
  5683. SmartArray.prototype.forEach = function (func) {
  5684. for (var index = 0; index < this.length; index++) {
  5685. func(this.data[index]);
  5686. }
  5687. };
  5688. SmartArray.prototype.sort = function (compareFn) {
  5689. this.data.sort(compareFn);
  5690. };
  5691. SmartArray.prototype.reset = function () {
  5692. this.length = 0;
  5693. };
  5694. SmartArray.prototype.dispose = function () {
  5695. this.reset();
  5696. if (this.data) {
  5697. this.data.length = 0;
  5698. this.data = [];
  5699. }
  5700. };
  5701. SmartArray.prototype.concat = function (array) {
  5702. if (array.length === 0) {
  5703. return;
  5704. }
  5705. if (this.length + array.length > this.data.length) {
  5706. this.data.length = (this.length + array.length) * 2;
  5707. }
  5708. for (var index = 0; index < array.length; index++) {
  5709. this.data[this.length++] = (array.data || array)[index];
  5710. }
  5711. };
  5712. SmartArray.prototype.indexOf = function (value) {
  5713. var position = this.data.indexOf(value);
  5714. if (position >= this.length) {
  5715. return -1;
  5716. }
  5717. return position;
  5718. };
  5719. SmartArray.prototype.contains = function (value) {
  5720. return this.data.indexOf(value) !== -1;
  5721. };
  5722. // Statics
  5723. SmartArray._GlobalId = 0;
  5724. return SmartArray;
  5725. }());
  5726. BABYLON.SmartArray = SmartArray;
  5727. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  5728. __extends(SmartArrayNoDuplicate, _super);
  5729. function SmartArrayNoDuplicate() {
  5730. var _this = _super !== null && _super.apply(this, arguments) || this;
  5731. _this._duplicateId = 0;
  5732. return _this;
  5733. }
  5734. SmartArrayNoDuplicate.prototype.push = function (value) {
  5735. _super.prototype.push.call(this, value);
  5736. if (!value.__smartArrayFlags) {
  5737. value.__smartArrayFlags = {};
  5738. }
  5739. value.__smartArrayFlags[this._id] = this._duplicateId;
  5740. };
  5741. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  5742. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  5743. return false;
  5744. }
  5745. this.push(value);
  5746. return true;
  5747. };
  5748. SmartArrayNoDuplicate.prototype.reset = function () {
  5749. _super.prototype.reset.call(this);
  5750. this._duplicateId++;
  5751. };
  5752. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  5753. if (array.length === 0) {
  5754. return;
  5755. }
  5756. if (this.length + array.length > this.data.length) {
  5757. this.data.length = (this.length + array.length) * 2;
  5758. }
  5759. for (var index = 0; index < array.length; index++) {
  5760. var item = (array.data || array)[index];
  5761. this.pushNoDuplicate(item);
  5762. }
  5763. };
  5764. return SmartArrayNoDuplicate;
  5765. }(SmartArray));
  5766. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  5767. })(BABYLON || (BABYLON = {}));
  5768. //# sourceMappingURL=babylon.smartArray.js.map
  5769. var BABYLON;
  5770. (function (BABYLON) {
  5771. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  5772. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  5773. var LoadFileError = /** @class */ (function (_super) {
  5774. __extends(LoadFileError, _super);
  5775. function LoadFileError(message, request) {
  5776. var _this = _super.call(this, message) || this;
  5777. _this.request = request;
  5778. _this.name = "LoadFileError";
  5779. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  5780. return _this;
  5781. }
  5782. // Polyfill for Object.setPrototypeOf if necessary.
  5783. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  5784. return LoadFileError;
  5785. }(Error));
  5786. BABYLON.LoadFileError = LoadFileError;
  5787. var RetryStrategy = /** @class */ (function () {
  5788. function RetryStrategy() {
  5789. }
  5790. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  5791. if (maxRetries === void 0) { maxRetries = 3; }
  5792. if (baseInterval === void 0) { baseInterval = 500; }
  5793. return function (url, request, retryIndex) {
  5794. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  5795. return -1;
  5796. }
  5797. return Math.pow(2, retryIndex) * baseInterval;
  5798. };
  5799. };
  5800. return RetryStrategy;
  5801. }());
  5802. BABYLON.RetryStrategy = RetryStrategy;
  5803. // Screenshots
  5804. var screenshotCanvas;
  5805. var cloneValue = function (source, destinationObject) {
  5806. if (!source)
  5807. return null;
  5808. if (source instanceof BABYLON.Mesh) {
  5809. return null;
  5810. }
  5811. if (source instanceof BABYLON.SubMesh) {
  5812. return source.clone(destinationObject);
  5813. }
  5814. else if (source.clone) {
  5815. return source.clone();
  5816. }
  5817. return null;
  5818. };
  5819. var Tools = /** @class */ (function () {
  5820. function Tools() {
  5821. }
  5822. /**
  5823. * Interpolates between a and b via alpha
  5824. * @param a The lower value (returned when alpha = 0)
  5825. * @param b The upper value (returned when alpha = 1)
  5826. * @param alpha The interpolation-factor
  5827. * @return The mixed value
  5828. */
  5829. Tools.Mix = function (a, b, alpha) {
  5830. return a * (1 - alpha) + b * alpha;
  5831. };
  5832. Tools.Instantiate = function (className) {
  5833. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  5834. return Tools.RegisteredExternalClasses[className];
  5835. }
  5836. var arr = className.split(".");
  5837. var fn = (window || this);
  5838. for (var i = 0, len = arr.length; i < len; i++) {
  5839. fn = fn[arr[i]];
  5840. }
  5841. if (typeof fn !== "function") {
  5842. return null;
  5843. }
  5844. return fn;
  5845. };
  5846. Tools.SetImmediate = function (action) {
  5847. if (window.setImmediate) {
  5848. window.setImmediate(action);
  5849. }
  5850. else {
  5851. setTimeout(action, 1);
  5852. }
  5853. };
  5854. Tools.IsExponentOfTwo = function (value) {
  5855. var count = 1;
  5856. do {
  5857. count *= 2;
  5858. } while (count < value);
  5859. return count === value;
  5860. };
  5861. /**
  5862. * Find the next highest power of two.
  5863. * @param x Number to start search from.
  5864. * @return Next highest power of two.
  5865. */
  5866. Tools.CeilingPOT = function (x) {
  5867. x--;
  5868. x |= x >> 1;
  5869. x |= x >> 2;
  5870. x |= x >> 4;
  5871. x |= x >> 8;
  5872. x |= x >> 16;
  5873. x++;
  5874. return x;
  5875. };
  5876. /**
  5877. * Find the next lowest power of two.
  5878. * @param x Number to start search from.
  5879. * @return Next lowest power of two.
  5880. */
  5881. Tools.FloorPOT = function (x) {
  5882. x = x | (x >> 1);
  5883. x = x | (x >> 2);
  5884. x = x | (x >> 4);
  5885. x = x | (x >> 8);
  5886. x = x | (x >> 16);
  5887. return x - (x >> 1);
  5888. };
  5889. /**
  5890. * Find the nearest power of two.
  5891. * @param x Number to start search from.
  5892. * @return Next nearest power of two.
  5893. */
  5894. Tools.NearestPOT = function (x) {
  5895. var c = Tools.CeilingPOT(x);
  5896. var f = Tools.FloorPOT(x);
  5897. return (c - x) > (x - f) ? f : c;
  5898. };
  5899. Tools.GetExponentOfTwo = function (value, max, mode) {
  5900. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  5901. var pot;
  5902. switch (mode) {
  5903. case BABYLON.Engine.SCALEMODE_FLOOR:
  5904. pot = Tools.FloorPOT(value);
  5905. break;
  5906. case BABYLON.Engine.SCALEMODE_NEAREST:
  5907. pot = Tools.NearestPOT(value);
  5908. break;
  5909. case BABYLON.Engine.SCALEMODE_CEILING:
  5910. default:
  5911. pot = Tools.CeilingPOT(value);
  5912. break;
  5913. }
  5914. return Math.min(pot, max);
  5915. };
  5916. Tools.GetFilename = function (path) {
  5917. var index = path.lastIndexOf("/");
  5918. if (index < 0)
  5919. return path;
  5920. return path.substring(index + 1);
  5921. };
  5922. Tools.GetFolderPath = function (uri) {
  5923. var index = uri.lastIndexOf("/");
  5924. if (index < 0)
  5925. return "";
  5926. return uri.substring(0, index + 1);
  5927. };
  5928. Tools.GetDOMTextContent = function (element) {
  5929. var result = "";
  5930. var child = element.firstChild;
  5931. while (child) {
  5932. if (child.nodeType === 3) {
  5933. result += child.textContent;
  5934. }
  5935. child = child.nextSibling;
  5936. }
  5937. return result;
  5938. };
  5939. Tools.ToDegrees = function (angle) {
  5940. return angle * 180 / Math.PI;
  5941. };
  5942. Tools.ToRadians = function (angle) {
  5943. return angle * Math.PI / 180;
  5944. };
  5945. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  5946. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  5947. var output = "";
  5948. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  5949. var i = 0;
  5950. var bytes = new Uint8Array(buffer);
  5951. while (i < bytes.length) {
  5952. chr1 = bytes[i++];
  5953. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  5954. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  5955. enc1 = chr1 >> 2;
  5956. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  5957. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  5958. enc4 = chr3 & 63;
  5959. if (isNaN(chr2)) {
  5960. enc3 = enc4 = 64;
  5961. }
  5962. else if (isNaN(chr3)) {
  5963. enc4 = 64;
  5964. }
  5965. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  5966. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  5967. }
  5968. return "data:image/png;base64," + output;
  5969. };
  5970. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  5971. if (bias === void 0) { bias = null; }
  5972. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5973. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  5974. for (var index = indexStart; index < indexStart + indexCount; index++) {
  5975. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  5976. minimum = BABYLON.Vector3.Minimize(current, minimum);
  5977. maximum = BABYLON.Vector3.Maximize(current, maximum);
  5978. }
  5979. if (bias) {
  5980. minimum.x -= minimum.x * bias.x + bias.y;
  5981. minimum.y -= minimum.y * bias.x + bias.y;
  5982. minimum.z -= minimum.z * bias.x + bias.y;
  5983. maximum.x += maximum.x * bias.x + bias.y;
  5984. maximum.y += maximum.y * bias.x + bias.y;
  5985. maximum.z += maximum.z * bias.x + bias.y;
  5986. }
  5987. return {
  5988. minimum: minimum,
  5989. maximum: maximum
  5990. };
  5991. };
  5992. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  5993. if (bias === void 0) { bias = null; }
  5994. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5995. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  5996. if (!stride) {
  5997. stride = 3;
  5998. }
  5999. for (var index = start; index < start + count; index++) {
  6000. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  6001. minimum = BABYLON.Vector3.Minimize(current, minimum);
  6002. maximum = BABYLON.Vector3.Maximize(current, maximum);
  6003. }
  6004. if (bias) {
  6005. minimum.x -= minimum.x * bias.x + bias.y;
  6006. minimum.y -= minimum.y * bias.x + bias.y;
  6007. minimum.z -= minimum.z * bias.x + bias.y;
  6008. maximum.x += maximum.x * bias.x + bias.y;
  6009. maximum.y += maximum.y * bias.x + bias.y;
  6010. maximum.z += maximum.z * bias.x + bias.y;
  6011. }
  6012. return {
  6013. minimum: minimum,
  6014. maximum: maximum
  6015. };
  6016. };
  6017. Tools.Vector2ArrayFeeder = function (array) {
  6018. return function (index) {
  6019. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  6020. var length = isFloatArray ? array.length / 2 : array.length;
  6021. if (index >= length) {
  6022. return null;
  6023. }
  6024. if (isFloatArray) {
  6025. var fa = array;
  6026. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  6027. }
  6028. var a = array;
  6029. return a[index];
  6030. };
  6031. };
  6032. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  6033. if (bias === void 0) { bias = null; }
  6034. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  6035. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  6036. var i = 0;
  6037. var cur = feeder(i++);
  6038. while (cur) {
  6039. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  6040. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  6041. cur = feeder(i++);
  6042. }
  6043. if (bias) {
  6044. minimum.x -= minimum.x * bias.x + bias.y;
  6045. minimum.y -= minimum.y * bias.x + bias.y;
  6046. maximum.x += maximum.x * bias.x + bias.y;
  6047. maximum.y += maximum.y * bias.x + bias.y;
  6048. }
  6049. return {
  6050. minimum: minimum,
  6051. maximum: maximum
  6052. };
  6053. };
  6054. Tools.MakeArray = function (obj, allowsNullUndefined) {
  6055. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  6056. return null;
  6057. return Array.isArray(obj) ? obj : [obj];
  6058. };
  6059. // Misc.
  6060. Tools.GetPointerPrefix = function () {
  6061. var eventPrefix = "pointer";
  6062. // Check if pointer events are supported
  6063. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  6064. eventPrefix = "mouse";
  6065. }
  6066. return eventPrefix;
  6067. };
  6068. /**
  6069. * @param func - the function to be called
  6070. * @param requester - the object that will request the next frame. Falls back to window.
  6071. */
  6072. Tools.QueueNewFrame = function (func, requester) {
  6073. if (!Tools.IsWindowObjectExist()) {
  6074. return setTimeout(func, 16);
  6075. }
  6076. if (!requester) {
  6077. requester = window;
  6078. }
  6079. if (requester.requestAnimationFrame) {
  6080. return requester.requestAnimationFrame(func);
  6081. }
  6082. else if (requester.msRequestAnimationFrame) {
  6083. return requester.msRequestAnimationFrame(func);
  6084. }
  6085. else if (requester.webkitRequestAnimationFrame) {
  6086. return requester.webkitRequestAnimationFrame(func);
  6087. }
  6088. else if (requester.mozRequestAnimationFrame) {
  6089. return requester.mozRequestAnimationFrame(func);
  6090. }
  6091. else if (requester.oRequestAnimationFrame) {
  6092. return requester.oRequestAnimationFrame(func);
  6093. }
  6094. else {
  6095. return window.setTimeout(func, 16);
  6096. }
  6097. };
  6098. Tools.RequestFullscreen = function (element) {
  6099. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  6100. if (!requestFunction)
  6101. return;
  6102. requestFunction.call(element);
  6103. };
  6104. Tools.ExitFullscreen = function () {
  6105. if (document.exitFullscreen) {
  6106. document.exitFullscreen();
  6107. }
  6108. else if (document.mozCancelFullScreen) {
  6109. document.mozCancelFullScreen();
  6110. }
  6111. else if (document.webkitCancelFullScreen) {
  6112. document.webkitCancelFullScreen();
  6113. }
  6114. else if (document.msCancelFullScreen) {
  6115. document.msCancelFullScreen();
  6116. }
  6117. };
  6118. Tools.SetCorsBehavior = function (url, element) {
  6119. if (url && url.indexOf("data:") === 0) {
  6120. return;
  6121. }
  6122. if (Tools.CorsBehavior) {
  6123. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  6124. element.crossOrigin = Tools.CorsBehavior;
  6125. }
  6126. else {
  6127. var result = Tools.CorsBehavior(url);
  6128. if (result) {
  6129. element.crossOrigin = result;
  6130. }
  6131. }
  6132. }
  6133. };
  6134. // External files
  6135. Tools.CleanUrl = function (url) {
  6136. url = url.replace(/#/mg, "%23");
  6137. return url;
  6138. };
  6139. Tools.LoadImage = function (url, onLoad, onError, database) {
  6140. if (url instanceof ArrayBuffer) {
  6141. url = Tools.EncodeArrayBufferTobase64(url);
  6142. }
  6143. url = Tools.CleanUrl(url);
  6144. url = Tools.PreprocessUrl(url);
  6145. var img = new Image();
  6146. Tools.SetCorsBehavior(url, img);
  6147. img.onload = function () {
  6148. onLoad(img);
  6149. };
  6150. img.onerror = function (err) {
  6151. Tools.Error("Error while trying to load image: " + url);
  6152. if (onError) {
  6153. onError("Error while trying to load image: " + url, err);
  6154. }
  6155. };
  6156. var noIndexedDB = function () {
  6157. img.src = url;
  6158. };
  6159. var loadFromIndexedDB = function () {
  6160. if (database) {
  6161. database.loadImageFromDB(url, img);
  6162. }
  6163. };
  6164. //ANY database to do!
  6165. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  6166. database.openAsync(loadFromIndexedDB, noIndexedDB);
  6167. }
  6168. else {
  6169. if (url.indexOf("file:") !== -1) {
  6170. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  6171. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  6172. try {
  6173. var blobURL;
  6174. try {
  6175. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  6176. }
  6177. catch (ex) {
  6178. // Chrome doesn't support oneTimeOnly parameter
  6179. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  6180. }
  6181. img.src = blobURL;
  6182. }
  6183. catch (e) {
  6184. img.src = "";
  6185. }
  6186. return img;
  6187. }
  6188. }
  6189. noIndexedDB();
  6190. }
  6191. return img;
  6192. };
  6193. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  6194. url = Tools.CleanUrl(url);
  6195. url = Tools.PreprocessUrl(url);
  6196. // If file and file input are set
  6197. if (url.indexOf("file:") !== -1) {
  6198. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  6199. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  6200. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  6201. }
  6202. }
  6203. var loadUrl = Tools.BaseUrl + url;
  6204. var aborted = false;
  6205. var fileRequest = {
  6206. onCompleteObservable: new BABYLON.Observable(),
  6207. abort: function () { return aborted = true; },
  6208. };
  6209. var requestFile = function () {
  6210. var request = new XMLHttpRequest();
  6211. var retryHandle = null;
  6212. fileRequest.abort = function () {
  6213. aborted = true;
  6214. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  6215. request.abort();
  6216. }
  6217. if (retryHandle !== null) {
  6218. clearTimeout(retryHandle);
  6219. retryHandle = null;
  6220. }
  6221. };
  6222. var retryLoop = function (retryIndex) {
  6223. request.open('GET', loadUrl, true);
  6224. if (useArrayBuffer) {
  6225. request.responseType = "arraybuffer";
  6226. }
  6227. if (onProgress) {
  6228. request.addEventListener("progress", onProgress);
  6229. }
  6230. var onLoadEnd = function () {
  6231. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  6232. };
  6233. request.addEventListener("loadend", onLoadEnd);
  6234. var onReadyStateChange = function () {
  6235. if (aborted) {
  6236. return;
  6237. }
  6238. // In case of undefined state in some browsers.
  6239. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  6240. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  6241. request.removeEventListener("readystatechange", onReadyStateChange);
  6242. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  6243. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  6244. return;
  6245. }
  6246. var retryStrategy = Tools.DefaultRetryStrategy;
  6247. if (retryStrategy) {
  6248. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  6249. if (waitTime !== -1) {
  6250. // Prevent the request from completing for retry.
  6251. request.removeEventListener("loadend", onLoadEnd);
  6252. request = new XMLHttpRequest();
  6253. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  6254. return;
  6255. }
  6256. }
  6257. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  6258. if (onError) {
  6259. onError(request, e);
  6260. }
  6261. else {
  6262. throw e;
  6263. }
  6264. }
  6265. };
  6266. request.addEventListener("readystatechange", onReadyStateChange);
  6267. request.send();
  6268. };
  6269. retryLoop(0);
  6270. };
  6271. // Caching all files
  6272. if (database && database.enableSceneOffline) {
  6273. var noIndexedDB_1 = function () {
  6274. if (!aborted) {
  6275. requestFile();
  6276. }
  6277. };
  6278. var loadFromIndexedDB = function () {
  6279. // TODO: database needs to support aborting and should return a IFileRequest
  6280. if (aborted) {
  6281. return;
  6282. }
  6283. if (database) {
  6284. database.loadFileFromDB(url, function (data) {
  6285. if (!aborted) {
  6286. onSuccess(data);
  6287. }
  6288. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  6289. }, onProgress ? function (event) {
  6290. if (!aborted) {
  6291. onProgress(event);
  6292. }
  6293. } : undefined, noIndexedDB_1, useArrayBuffer);
  6294. }
  6295. };
  6296. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  6297. }
  6298. else {
  6299. requestFile();
  6300. }
  6301. return fileRequest;
  6302. };
  6303. /**
  6304. * Load a script (identified by an url). When the url returns, the
  6305. * content of this file is added into a new script element, attached to the DOM (body element)
  6306. */
  6307. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  6308. var head = document.getElementsByTagName('head')[0];
  6309. var script = document.createElement('script');
  6310. script.type = 'text/javascript';
  6311. script.src = scriptUrl;
  6312. script.onload = function () {
  6313. if (onSuccess) {
  6314. onSuccess();
  6315. }
  6316. };
  6317. script.onerror = function (e) {
  6318. if (onError) {
  6319. onError("Unable to load script", e);
  6320. }
  6321. };
  6322. head.appendChild(script);
  6323. };
  6324. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  6325. var reader = new FileReader();
  6326. var request = {
  6327. onCompleteObservable: new BABYLON.Observable(),
  6328. abort: function () { return reader.abort(); },
  6329. };
  6330. reader.onloadend = function (e) {
  6331. request.onCompleteObservable.notifyObservers(request);
  6332. };
  6333. reader.onload = function (e) {
  6334. //target doesn't have result from ts 1.3
  6335. callback(e.target['result']);
  6336. };
  6337. reader.onprogress = progressCallback;
  6338. reader.readAsDataURL(fileToLoad);
  6339. return request;
  6340. };
  6341. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  6342. var reader = new FileReader();
  6343. var request = {
  6344. onCompleteObservable: new BABYLON.Observable(),
  6345. abort: function () { return reader.abort(); },
  6346. };
  6347. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  6348. reader.onerror = function (e) {
  6349. Tools.Log("Error while reading file: " + fileToLoad.name);
  6350. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  6351. };
  6352. reader.onload = function (e) {
  6353. //target doesn't have result from ts 1.3
  6354. callback(e.target['result']);
  6355. };
  6356. if (progressCallBack) {
  6357. reader.onprogress = progressCallBack;
  6358. }
  6359. if (!useArrayBuffer) {
  6360. // Asynchronous read
  6361. reader.readAsText(fileToLoad);
  6362. }
  6363. else {
  6364. reader.readAsArrayBuffer(fileToLoad);
  6365. }
  6366. return request;
  6367. };
  6368. //returns a downloadable url to a file content.
  6369. Tools.FileAsURL = function (content) {
  6370. var fileBlob = new Blob([content]);
  6371. var url = window.URL || window.webkitURL;
  6372. var link = url.createObjectURL(fileBlob);
  6373. return link;
  6374. };
  6375. // Misc.
  6376. Tools.Format = function (value, decimals) {
  6377. if (decimals === void 0) { decimals = 2; }
  6378. return value.toFixed(decimals);
  6379. };
  6380. Tools.CheckExtends = function (v, min, max) {
  6381. if (v.x < min.x)
  6382. min.x = v.x;
  6383. if (v.y < min.y)
  6384. min.y = v.y;
  6385. if (v.z < min.z)
  6386. min.z = v.z;
  6387. if (v.x > max.x)
  6388. max.x = v.x;
  6389. if (v.y > max.y)
  6390. max.y = v.y;
  6391. if (v.z > max.z)
  6392. max.z = v.z;
  6393. };
  6394. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  6395. for (var prop in source) {
  6396. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  6397. continue;
  6398. }
  6399. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  6400. continue;
  6401. }
  6402. var sourceValue = source[prop];
  6403. var typeOfSourceValue = typeof sourceValue;
  6404. if (typeOfSourceValue === "function") {
  6405. continue;
  6406. }
  6407. if (typeOfSourceValue === "object") {
  6408. if (sourceValue instanceof Array) {
  6409. destination[prop] = [];
  6410. if (sourceValue.length > 0) {
  6411. if (typeof sourceValue[0] == "object") {
  6412. for (var index = 0; index < sourceValue.length; index++) {
  6413. var clonedValue = cloneValue(sourceValue[index], destination);
  6414. if (destination[prop].indexOf(clonedValue) === -1) {
  6415. destination[prop].push(clonedValue);
  6416. }
  6417. }
  6418. }
  6419. else {
  6420. destination[prop] = sourceValue.slice(0);
  6421. }
  6422. }
  6423. }
  6424. else {
  6425. destination[prop] = cloneValue(sourceValue, destination);
  6426. }
  6427. }
  6428. else {
  6429. destination[prop] = sourceValue;
  6430. }
  6431. }
  6432. };
  6433. Tools.IsEmpty = function (obj) {
  6434. for (var i in obj) {
  6435. if (obj.hasOwnProperty(i)) {
  6436. return false;
  6437. }
  6438. }
  6439. return true;
  6440. };
  6441. Tools.RegisterTopRootEvents = function (events) {
  6442. for (var index = 0; index < events.length; index++) {
  6443. var event = events[index];
  6444. window.addEventListener(event.name, event.handler, false);
  6445. try {
  6446. if (window.parent) {
  6447. window.parent.addEventListener(event.name, event.handler, false);
  6448. }
  6449. }
  6450. catch (e) {
  6451. // Silently fails...
  6452. }
  6453. }
  6454. };
  6455. Tools.UnregisterTopRootEvents = function (events) {
  6456. for (var index = 0; index < events.length; index++) {
  6457. var event = events[index];
  6458. window.removeEventListener(event.name, event.handler);
  6459. try {
  6460. if (window.parent) {
  6461. window.parent.removeEventListener(event.name, event.handler);
  6462. }
  6463. }
  6464. catch (e) {
  6465. // Silently fails...
  6466. }
  6467. }
  6468. };
  6469. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  6470. if (mimeType === void 0) { mimeType = "image/png"; }
  6471. // Read the contents of the framebuffer
  6472. var numberOfChannelsByLine = width * 4;
  6473. var halfHeight = height / 2;
  6474. //Reading datas from WebGL
  6475. var data = engine.readPixels(0, 0, width, height);
  6476. //To flip image on Y axis.
  6477. for (var i = 0; i < halfHeight; i++) {
  6478. for (var j = 0; j < numberOfChannelsByLine; j++) {
  6479. var currentCell = j + i * numberOfChannelsByLine;
  6480. var targetLine = height - i - 1;
  6481. var targetCell = j + targetLine * numberOfChannelsByLine;
  6482. var temp = data[currentCell];
  6483. data[currentCell] = data[targetCell];
  6484. data[targetCell] = temp;
  6485. }
  6486. }
  6487. // Create a 2D canvas to store the result
  6488. if (!screenshotCanvas) {
  6489. screenshotCanvas = document.createElement('canvas');
  6490. }
  6491. screenshotCanvas.width = width;
  6492. screenshotCanvas.height = height;
  6493. var context = screenshotCanvas.getContext('2d');
  6494. if (context) {
  6495. // Copy the pixels to a 2D canvas
  6496. var imageData = context.createImageData(width, height);
  6497. var castData = (imageData.data);
  6498. castData.set(data);
  6499. context.putImageData(imageData, 0, 0);
  6500. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  6501. }
  6502. };
  6503. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  6504. if (mimeType === void 0) { mimeType = "image/png"; }
  6505. var base64Image = screenshotCanvas.toDataURL(mimeType);
  6506. if (successCallback) {
  6507. successCallback(base64Image);
  6508. }
  6509. else {
  6510. // We need HTMLCanvasElement.toBlob for HD screenshots
  6511. if (!screenshotCanvas.toBlob) {
  6512. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  6513. screenshotCanvas.toBlob = function (callback, type, quality) {
  6514. var _this = this;
  6515. setTimeout(function () {
  6516. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  6517. for (var i = 0; i < len; i++) {
  6518. arr[i] = binStr.charCodeAt(i);
  6519. }
  6520. callback(new Blob([arr], { type: type || 'image/png' }));
  6521. });
  6522. };
  6523. }
  6524. screenshotCanvas.toBlob(function (blob) {
  6525. var url = URL.createObjectURL(blob);
  6526. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  6527. if (("download" in document.createElement("a"))) {
  6528. var a = window.document.createElement("a");
  6529. a.href = url;
  6530. if (fileName) {
  6531. a.setAttribute("download", fileName);
  6532. }
  6533. else {
  6534. var date = new Date();
  6535. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  6536. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  6537. }
  6538. window.document.body.appendChild(a);
  6539. a.addEventListener("click", function () {
  6540. if (a.parentElement) {
  6541. a.parentElement.removeChild(a);
  6542. }
  6543. });
  6544. a.click();
  6545. }
  6546. else {
  6547. var newWindow = window.open("");
  6548. if (!newWindow)
  6549. return;
  6550. var img = newWindow.document.createElement("img");
  6551. img.onload = function () {
  6552. // no longer need to read the blob so it's revoked
  6553. URL.revokeObjectURL(url);
  6554. };
  6555. img.src = url;
  6556. newWindow.document.body.appendChild(img);
  6557. }
  6558. });
  6559. }
  6560. };
  6561. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  6562. if (mimeType === void 0) { mimeType = "image/png"; }
  6563. var width;
  6564. var height;
  6565. // If a precision value is specified
  6566. if (size.precision) {
  6567. width = Math.round(engine.getRenderWidth() * size.precision);
  6568. height = Math.round(width / engine.getAspectRatio(camera));
  6569. }
  6570. else if (size.width && size.height) {
  6571. width = size.width;
  6572. height = size.height;
  6573. }
  6574. else if (size.width && !size.height) {
  6575. width = size.width;
  6576. height = Math.round(width / engine.getAspectRatio(camera));
  6577. }
  6578. else if (size.height && !size.width) {
  6579. height = size.height;
  6580. width = Math.round(height * engine.getAspectRatio(camera));
  6581. }
  6582. else if (!isNaN(size)) {
  6583. height = size;
  6584. width = size;
  6585. }
  6586. else {
  6587. Tools.Error("Invalid 'size' parameter !");
  6588. return;
  6589. }
  6590. if (!screenshotCanvas) {
  6591. screenshotCanvas = document.createElement('canvas');
  6592. }
  6593. screenshotCanvas.width = width;
  6594. screenshotCanvas.height = height;
  6595. var renderContext = screenshotCanvas.getContext("2d");
  6596. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  6597. var newWidth = width;
  6598. var newHeight = newWidth / ratio;
  6599. if (newHeight > height) {
  6600. newHeight = height;
  6601. newWidth = newHeight * ratio;
  6602. }
  6603. var offsetX = Math.max(0, width - newWidth) / 2;
  6604. var offsetY = Math.max(0, height - newHeight) / 2;
  6605. var renderingCanvas = engine.getRenderingCanvas();
  6606. if (renderContext && renderingCanvas) {
  6607. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  6608. }
  6609. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  6610. };
  6611. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  6612. if (mimeType === void 0) { mimeType = "image/png"; }
  6613. if (samples === void 0) { samples = 1; }
  6614. if (antialiasing === void 0) { antialiasing = false; }
  6615. var width;
  6616. var height;
  6617. //If a precision value is specified
  6618. if (size.precision) {
  6619. width = Math.round(engine.getRenderWidth() * size.precision);
  6620. height = Math.round(width / engine.getAspectRatio(camera));
  6621. size = { width: width, height: height };
  6622. }
  6623. else if (size.width && size.height) {
  6624. width = size.width;
  6625. height = size.height;
  6626. }
  6627. else if (size.width && !size.height) {
  6628. width = size.width;
  6629. height = Math.round(width / engine.getAspectRatio(camera));
  6630. size = { width: width, height: height };
  6631. }
  6632. else if (size.height && !size.width) {
  6633. height = size.height;
  6634. width = Math.round(height * engine.getAspectRatio(camera));
  6635. size = { width: width, height: height };
  6636. }
  6637. else if (!isNaN(size)) {
  6638. height = size;
  6639. width = size;
  6640. }
  6641. else {
  6642. Tools.Error("Invalid 'size' parameter !");
  6643. return;
  6644. }
  6645. var scene = camera.getScene();
  6646. var previousCamera = null;
  6647. if (scene.activeCamera !== camera) {
  6648. previousCamera = scene.activeCamera;
  6649. scene.activeCamera = camera;
  6650. }
  6651. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  6652. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  6653. texture.renderList = null;
  6654. texture.samples = samples;
  6655. if (antialiasing) {
  6656. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  6657. }
  6658. texture.onAfterRenderObservable.add(function () {
  6659. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  6660. });
  6661. scene.incrementRenderId();
  6662. scene.resetCachedMaterial();
  6663. texture.render(true);
  6664. texture.dispose();
  6665. if (previousCamera) {
  6666. scene.activeCamera = previousCamera;
  6667. }
  6668. camera.getProjectionMatrix(true); // Force cache refresh;
  6669. };
  6670. // XHR response validator for local file scenario
  6671. Tools.ValidateXHRData = function (xhr, dataType) {
  6672. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  6673. if (dataType === void 0) { dataType = 7; }
  6674. try {
  6675. if (dataType & 1) {
  6676. if (xhr.responseText && xhr.responseText.length > 0) {
  6677. return true;
  6678. }
  6679. else if (dataType === 1) {
  6680. return false;
  6681. }
  6682. }
  6683. if (dataType & 2) {
  6684. // Check header width and height since there is no "TGA" magic number
  6685. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  6686. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  6687. return true;
  6688. }
  6689. else if (dataType === 2) {
  6690. return false;
  6691. }
  6692. }
  6693. if (dataType & 4) {
  6694. // Check for the "DDS" magic number
  6695. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  6696. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  6697. return true;
  6698. }
  6699. else {
  6700. return false;
  6701. }
  6702. }
  6703. }
  6704. catch (e) {
  6705. // Global protection
  6706. }
  6707. return false;
  6708. };
  6709. /**
  6710. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  6711. * Be aware Math.random() could cause collisions, but:
  6712. * "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"
  6713. */
  6714. Tools.RandomId = function () {
  6715. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  6716. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  6717. return v.toString(16);
  6718. });
  6719. };
  6720. Object.defineProperty(Tools, "NoneLogLevel", {
  6721. get: function () {
  6722. return Tools._NoneLogLevel;
  6723. },
  6724. enumerable: true,
  6725. configurable: true
  6726. });
  6727. Object.defineProperty(Tools, "MessageLogLevel", {
  6728. get: function () {
  6729. return Tools._MessageLogLevel;
  6730. },
  6731. enumerable: true,
  6732. configurable: true
  6733. });
  6734. Object.defineProperty(Tools, "WarningLogLevel", {
  6735. get: function () {
  6736. return Tools._WarningLogLevel;
  6737. },
  6738. enumerable: true,
  6739. configurable: true
  6740. });
  6741. Object.defineProperty(Tools, "ErrorLogLevel", {
  6742. get: function () {
  6743. return Tools._ErrorLogLevel;
  6744. },
  6745. enumerable: true,
  6746. configurable: true
  6747. });
  6748. Object.defineProperty(Tools, "AllLogLevel", {
  6749. get: function () {
  6750. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  6751. },
  6752. enumerable: true,
  6753. configurable: true
  6754. });
  6755. Tools._AddLogEntry = function (entry) {
  6756. Tools._LogCache = entry + Tools._LogCache;
  6757. if (Tools.OnNewCacheEntry) {
  6758. Tools.OnNewCacheEntry(entry);
  6759. }
  6760. };
  6761. Tools._FormatMessage = function (message) {
  6762. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  6763. var date = new Date();
  6764. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  6765. };
  6766. Tools._LogDisabled = function (message) {
  6767. // nothing to do
  6768. };
  6769. Tools._LogEnabled = function (message) {
  6770. var formattedMessage = Tools._FormatMessage(message);
  6771. console.log("BJS - " + formattedMessage);
  6772. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  6773. Tools._AddLogEntry(entry);
  6774. };
  6775. Tools._WarnDisabled = function (message) {
  6776. // nothing to do
  6777. };
  6778. Tools._WarnEnabled = function (message) {
  6779. var formattedMessage = Tools._FormatMessage(message);
  6780. console.warn("BJS - " + formattedMessage);
  6781. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  6782. Tools._AddLogEntry(entry);
  6783. };
  6784. Tools._ErrorDisabled = function (message) {
  6785. // nothing to do
  6786. };
  6787. Tools._ErrorEnabled = function (message) {
  6788. Tools.errorsCount++;
  6789. var formattedMessage = Tools._FormatMessage(message);
  6790. console.error("BJS - " + formattedMessage);
  6791. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  6792. Tools._AddLogEntry(entry);
  6793. };
  6794. Object.defineProperty(Tools, "LogCache", {
  6795. get: function () {
  6796. return Tools._LogCache;
  6797. },
  6798. enumerable: true,
  6799. configurable: true
  6800. });
  6801. Tools.ClearLogCache = function () {
  6802. Tools._LogCache = "";
  6803. Tools.errorsCount = 0;
  6804. };
  6805. Object.defineProperty(Tools, "LogLevels", {
  6806. set: function (level) {
  6807. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  6808. Tools.Log = Tools._LogEnabled;
  6809. }
  6810. else {
  6811. Tools.Log = Tools._LogDisabled;
  6812. }
  6813. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  6814. Tools.Warn = Tools._WarnEnabled;
  6815. }
  6816. else {
  6817. Tools.Warn = Tools._WarnDisabled;
  6818. }
  6819. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  6820. Tools.Error = Tools._ErrorEnabled;
  6821. }
  6822. else {
  6823. Tools.Error = Tools._ErrorDisabled;
  6824. }
  6825. },
  6826. enumerable: true,
  6827. configurable: true
  6828. });
  6829. Tools.IsWindowObjectExist = function () {
  6830. return (typeof window) !== "undefined";
  6831. };
  6832. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  6833. get: function () {
  6834. return Tools._PerformanceNoneLogLevel;
  6835. },
  6836. enumerable: true,
  6837. configurable: true
  6838. });
  6839. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  6840. get: function () {
  6841. return Tools._PerformanceUserMarkLogLevel;
  6842. },
  6843. enumerable: true,
  6844. configurable: true
  6845. });
  6846. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  6847. get: function () {
  6848. return Tools._PerformanceConsoleLogLevel;
  6849. },
  6850. enumerable: true,
  6851. configurable: true
  6852. });
  6853. Object.defineProperty(Tools, "PerformanceLogLevel", {
  6854. set: function (level) {
  6855. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  6856. Tools.StartPerformanceCounter = Tools._StartUserMark;
  6857. Tools.EndPerformanceCounter = Tools._EndUserMark;
  6858. return;
  6859. }
  6860. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  6861. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  6862. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  6863. return;
  6864. }
  6865. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6866. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6867. },
  6868. enumerable: true,
  6869. configurable: true
  6870. });
  6871. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  6872. };
  6873. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  6874. };
  6875. Tools._StartUserMark = function (counterName, condition) {
  6876. if (condition === void 0) { condition = true; }
  6877. if (!Tools._performance) {
  6878. if (!Tools.IsWindowObjectExist()) {
  6879. return;
  6880. }
  6881. Tools._performance = window.performance;
  6882. }
  6883. if (!condition || !Tools._performance.mark) {
  6884. return;
  6885. }
  6886. Tools._performance.mark(counterName + "-Begin");
  6887. };
  6888. Tools._EndUserMark = function (counterName, condition) {
  6889. if (condition === void 0) { condition = true; }
  6890. if (!condition || !Tools._performance.mark) {
  6891. return;
  6892. }
  6893. Tools._performance.mark(counterName + "-End");
  6894. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  6895. };
  6896. Tools._StartPerformanceConsole = function (counterName, condition) {
  6897. if (condition === void 0) { condition = true; }
  6898. if (!condition) {
  6899. return;
  6900. }
  6901. Tools._StartUserMark(counterName, condition);
  6902. if (console.time) {
  6903. console.time(counterName);
  6904. }
  6905. };
  6906. Tools._EndPerformanceConsole = function (counterName, condition) {
  6907. if (condition === void 0) { condition = true; }
  6908. if (!condition) {
  6909. return;
  6910. }
  6911. Tools._EndUserMark(counterName, condition);
  6912. if (console.time) {
  6913. console.timeEnd(counterName);
  6914. }
  6915. };
  6916. Object.defineProperty(Tools, "Now", {
  6917. get: function () {
  6918. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  6919. return window.performance.now();
  6920. }
  6921. return new Date().getTime();
  6922. },
  6923. enumerable: true,
  6924. configurable: true
  6925. });
  6926. /**
  6927. * This method will return the name of the class used to create the instance of the given object.
  6928. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  6929. * @param object the object to get the class name from
  6930. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  6931. */
  6932. Tools.GetClassName = function (object, isType) {
  6933. if (isType === void 0) { isType = false; }
  6934. var name = null;
  6935. if (!isType && object.getClassName) {
  6936. name = object.getClassName();
  6937. }
  6938. else {
  6939. if (object instanceof Object) {
  6940. var classObj = isType ? object : Object.getPrototypeOf(object);
  6941. name = classObj.constructor["__bjsclassName__"];
  6942. }
  6943. if (!name) {
  6944. name = typeof object;
  6945. }
  6946. }
  6947. return name;
  6948. };
  6949. Tools.First = function (array, predicate) {
  6950. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  6951. var el = array_1[_i];
  6952. if (predicate(el)) {
  6953. return el;
  6954. }
  6955. }
  6956. return null;
  6957. };
  6958. /**
  6959. * This method will return the name of the full name of the class, including its owning module (if any).
  6960. * 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).
  6961. * @param object the object to get the class name from
  6962. * @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.
  6963. */
  6964. Tools.getFullClassName = function (object, isType) {
  6965. if (isType === void 0) { isType = false; }
  6966. var className = null;
  6967. var moduleName = null;
  6968. if (!isType && object.getClassName) {
  6969. className = object.getClassName();
  6970. }
  6971. else {
  6972. if (object instanceof Object) {
  6973. var classObj = isType ? object : Object.getPrototypeOf(object);
  6974. className = classObj.constructor["__bjsclassName__"];
  6975. moduleName = classObj.constructor["__bjsmoduleName__"];
  6976. }
  6977. if (!className) {
  6978. className = typeof object;
  6979. }
  6980. }
  6981. if (!className) {
  6982. return null;
  6983. }
  6984. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  6985. };
  6986. /**
  6987. * 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.
  6988. * @param array
  6989. */
  6990. Tools.arrayOrStringFeeder = function (array) {
  6991. return function (index) {
  6992. if (index >= array.length) {
  6993. return null;
  6994. }
  6995. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  6996. if (val && val.getHashCode) {
  6997. val = val.getHashCode();
  6998. }
  6999. if (typeof val === "string") {
  7000. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  7001. }
  7002. return val;
  7003. };
  7004. };
  7005. /**
  7006. * Compute the hashCode of a stream of number
  7007. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  7008. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  7009. * @return the hash code computed
  7010. */
  7011. Tools.hashCodeFromStream = function (feeder) {
  7012. // Based from here: http://stackoverflow.com/a/7616484/802124
  7013. var hash = 0;
  7014. var index = 0;
  7015. var chr = feeder(index++);
  7016. while (chr != null) {
  7017. hash = ((hash << 5) - hash) + chr;
  7018. hash |= 0; // Convert to 32bit integer
  7019. chr = feeder(index++);
  7020. }
  7021. return hash;
  7022. };
  7023. Tools.BaseUrl = "";
  7024. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  7025. /**
  7026. * Default behaviour for cors in the application.
  7027. * It can be a string if the expected behavior is identical in the entire app.
  7028. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  7029. */
  7030. Tools.CorsBehavior = "anonymous";
  7031. Tools.UseFallbackTexture = true;
  7032. /**
  7033. * Use this object to register external classes like custom textures or material
  7034. * to allow the laoders to instantiate them
  7035. */
  7036. Tools.RegisteredExternalClasses = {};
  7037. // Used in case of a texture loading problem
  7038. 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";
  7039. Tools.PreprocessUrl = function (url) {
  7040. return url;
  7041. };
  7042. // Logs
  7043. Tools._NoneLogLevel = 0;
  7044. Tools._MessageLogLevel = 1;
  7045. Tools._WarningLogLevel = 2;
  7046. Tools._ErrorLogLevel = 4;
  7047. Tools._LogCache = "";
  7048. Tools.errorsCount = 0;
  7049. Tools.Log = Tools._LogEnabled;
  7050. Tools.Warn = Tools._WarnEnabled;
  7051. Tools.Error = Tools._ErrorEnabled;
  7052. // Performances
  7053. Tools._PerformanceNoneLogLevel = 0;
  7054. Tools._PerformanceUserMarkLogLevel = 1;
  7055. Tools._PerformanceConsoleLogLevel = 2;
  7056. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  7057. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  7058. return Tools;
  7059. }());
  7060. BABYLON.Tools = Tools;
  7061. /**
  7062. * This class is used to track a performance counter which is number based.
  7063. * The user has access to many properties which give statistics of different nature
  7064. *
  7065. * The implementer can track two kinds of Performance Counter: time and count
  7066. * 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.
  7067. * 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.
  7068. */
  7069. var PerfCounter = /** @class */ (function () {
  7070. function PerfCounter() {
  7071. this._startMonitoringTime = 0;
  7072. this._min = 0;
  7073. this._max = 0;
  7074. this._average = 0;
  7075. this._lastSecAverage = 0;
  7076. this._current = 0;
  7077. this._totalValueCount = 0;
  7078. this._totalAccumulated = 0;
  7079. this._lastSecAccumulated = 0;
  7080. this._lastSecTime = 0;
  7081. this._lastSecValueCount = 0;
  7082. }
  7083. Object.defineProperty(PerfCounter.prototype, "min", {
  7084. /**
  7085. * Returns the smallest value ever
  7086. */
  7087. get: function () {
  7088. return this._min;
  7089. },
  7090. enumerable: true,
  7091. configurable: true
  7092. });
  7093. Object.defineProperty(PerfCounter.prototype, "max", {
  7094. /**
  7095. * Returns the biggest value ever
  7096. */
  7097. get: function () {
  7098. return this._max;
  7099. },
  7100. enumerable: true,
  7101. configurable: true
  7102. });
  7103. Object.defineProperty(PerfCounter.prototype, "average", {
  7104. /**
  7105. * Returns the average value since the performance counter is running
  7106. */
  7107. get: function () {
  7108. return this._average;
  7109. },
  7110. enumerable: true,
  7111. configurable: true
  7112. });
  7113. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  7114. /**
  7115. * Returns the average value of the last second the counter was monitored
  7116. */
  7117. get: function () {
  7118. return this._lastSecAverage;
  7119. },
  7120. enumerable: true,
  7121. configurable: true
  7122. });
  7123. Object.defineProperty(PerfCounter.prototype, "current", {
  7124. /**
  7125. * Returns the current value
  7126. */
  7127. get: function () {
  7128. return this._current;
  7129. },
  7130. enumerable: true,
  7131. configurable: true
  7132. });
  7133. Object.defineProperty(PerfCounter.prototype, "total", {
  7134. get: function () {
  7135. return this._totalAccumulated;
  7136. },
  7137. enumerable: true,
  7138. configurable: true
  7139. });
  7140. Object.defineProperty(PerfCounter.prototype, "count", {
  7141. get: function () {
  7142. return this._totalValueCount;
  7143. },
  7144. enumerable: true,
  7145. configurable: true
  7146. });
  7147. /**
  7148. * Call this method to start monitoring a new frame.
  7149. * 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.
  7150. */
  7151. PerfCounter.prototype.fetchNewFrame = function () {
  7152. this._totalValueCount++;
  7153. this._current = 0;
  7154. this._lastSecValueCount++;
  7155. };
  7156. /**
  7157. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  7158. * @param newCount the count value to add to the monitored count
  7159. * @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.
  7160. */
  7161. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  7162. if (!PerfCounter.Enabled) {
  7163. return;
  7164. }
  7165. this._current += newCount;
  7166. if (fetchResult) {
  7167. this._fetchResult();
  7168. }
  7169. };
  7170. /**
  7171. * Start monitoring this performance counter
  7172. */
  7173. PerfCounter.prototype.beginMonitoring = function () {
  7174. if (!PerfCounter.Enabled) {
  7175. return;
  7176. }
  7177. this._startMonitoringTime = Tools.Now;
  7178. };
  7179. /**
  7180. * Compute the time lapsed since the previous beginMonitoring() call.
  7181. * @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
  7182. */
  7183. PerfCounter.prototype.endMonitoring = function (newFrame) {
  7184. if (newFrame === void 0) { newFrame = true; }
  7185. if (!PerfCounter.Enabled) {
  7186. return;
  7187. }
  7188. if (newFrame) {
  7189. this.fetchNewFrame();
  7190. }
  7191. var currentTime = Tools.Now;
  7192. this._current = currentTime - this._startMonitoringTime;
  7193. if (newFrame) {
  7194. this._fetchResult();
  7195. }
  7196. };
  7197. PerfCounter.prototype._fetchResult = function () {
  7198. this._totalAccumulated += this._current;
  7199. this._lastSecAccumulated += this._current;
  7200. // Min/Max update
  7201. this._min = Math.min(this._min, this._current);
  7202. this._max = Math.max(this._max, this._current);
  7203. this._average = this._totalAccumulated / this._totalValueCount;
  7204. // Reset last sec?
  7205. var now = Tools.Now;
  7206. if ((now - this._lastSecTime) > 1000) {
  7207. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  7208. this._lastSecTime = now;
  7209. this._lastSecAccumulated = 0;
  7210. this._lastSecValueCount = 0;
  7211. }
  7212. };
  7213. PerfCounter.Enabled = true;
  7214. return PerfCounter;
  7215. }());
  7216. BABYLON.PerfCounter = PerfCounter;
  7217. /**
  7218. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  7219. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  7220. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  7221. * @param name The name of the class, case should be preserved
  7222. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  7223. */
  7224. function className(name, module) {
  7225. return function (target) {
  7226. target["__bjsclassName__"] = name;
  7227. target["__bjsmoduleName__"] = (module != null) ? module : null;
  7228. };
  7229. }
  7230. BABYLON.className = className;
  7231. /**
  7232. * An implementation of a loop for asynchronous functions.
  7233. */
  7234. var AsyncLoop = /** @class */ (function () {
  7235. /**
  7236. * Constroctor.
  7237. * @param iterations the number of iterations.
  7238. * @param _fn the function to run each iteration
  7239. * @param _successCallback the callback that will be called upon succesful execution
  7240. * @param offset starting offset.
  7241. */
  7242. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  7243. if (offset === void 0) { offset = 0; }
  7244. this.iterations = iterations;
  7245. this._fn = _fn;
  7246. this._successCallback = _successCallback;
  7247. this.index = offset - 1;
  7248. this._done = false;
  7249. }
  7250. /**
  7251. * Execute the next iteration. Must be called after the last iteration was finished.
  7252. */
  7253. AsyncLoop.prototype.executeNext = function () {
  7254. if (!this._done) {
  7255. if (this.index + 1 < this.iterations) {
  7256. ++this.index;
  7257. this._fn(this);
  7258. }
  7259. else {
  7260. this.breakLoop();
  7261. }
  7262. }
  7263. };
  7264. /**
  7265. * Break the loop and run the success callback.
  7266. */
  7267. AsyncLoop.prototype.breakLoop = function () {
  7268. this._done = true;
  7269. this._successCallback();
  7270. };
  7271. /**
  7272. * Helper function
  7273. */
  7274. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  7275. if (offset === void 0) { offset = 0; }
  7276. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  7277. loop.executeNext();
  7278. return loop;
  7279. };
  7280. /**
  7281. * A for-loop that will run a given number of iterations synchronous and the rest async.
  7282. * @param iterations total number of iterations
  7283. * @param syncedIterations number of synchronous iterations in each async iteration.
  7284. * @param fn the function to call each iteration.
  7285. * @param callback a success call back that will be called when iterating stops.
  7286. * @param breakFunction a break condition (optional)
  7287. * @param timeout timeout settings for the setTimeout function. default - 0.
  7288. * @constructor
  7289. */
  7290. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  7291. if (timeout === void 0) { timeout = 0; }
  7292. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  7293. if (breakFunction && breakFunction())
  7294. loop.breakLoop();
  7295. else {
  7296. setTimeout(function () {
  7297. for (var i = 0; i < syncedIterations; ++i) {
  7298. var iteration = (loop.index * syncedIterations) + i;
  7299. if (iteration >= iterations)
  7300. break;
  7301. fn(iteration);
  7302. if (breakFunction && breakFunction()) {
  7303. loop.breakLoop();
  7304. break;
  7305. }
  7306. }
  7307. loop.executeNext();
  7308. }, timeout);
  7309. }
  7310. }, callback);
  7311. };
  7312. return AsyncLoop;
  7313. }());
  7314. BABYLON.AsyncLoop = AsyncLoop;
  7315. })(BABYLON || (BABYLON = {}));
  7316. //# sourceMappingURL=babylon.tools.js.map
  7317. var BABYLON;
  7318. (function (BABYLON) {
  7319. var Internals;
  7320. (function (Internals) {
  7321. var _AlphaState = /** @class */ (function () {
  7322. /**
  7323. * Initializes the state.
  7324. */
  7325. function _AlphaState() {
  7326. this._isAlphaBlendDirty = false;
  7327. this._isBlendFunctionParametersDirty = false;
  7328. this._isBlendEquationParametersDirty = false;
  7329. this._isBlendConstantsDirty = false;
  7330. this._alphaBlend = false;
  7331. this._blendFunctionParameters = new Array(4);
  7332. this._blendEquationParameters = new Array(2);
  7333. this._blendConstants = new Array(4);
  7334. this.reset();
  7335. }
  7336. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  7337. get: function () {
  7338. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  7339. },
  7340. enumerable: true,
  7341. configurable: true
  7342. });
  7343. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  7344. get: function () {
  7345. return this._alphaBlend;
  7346. },
  7347. set: function (value) {
  7348. if (this._alphaBlend === value) {
  7349. return;
  7350. }
  7351. this._alphaBlend = value;
  7352. this._isAlphaBlendDirty = true;
  7353. },
  7354. enumerable: true,
  7355. configurable: true
  7356. });
  7357. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  7358. if (this._blendConstants[0] === r &&
  7359. this._blendConstants[1] === g &&
  7360. this._blendConstants[2] === b &&
  7361. this._blendConstants[3] === a) {
  7362. return;
  7363. }
  7364. this._blendConstants[0] = r;
  7365. this._blendConstants[1] = g;
  7366. this._blendConstants[2] = b;
  7367. this._blendConstants[3] = a;
  7368. this._isBlendConstantsDirty = true;
  7369. };
  7370. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  7371. if (this._blendFunctionParameters[0] === value0 &&
  7372. this._blendFunctionParameters[1] === value1 &&
  7373. this._blendFunctionParameters[2] === value2 &&
  7374. this._blendFunctionParameters[3] === value3) {
  7375. return;
  7376. }
  7377. this._blendFunctionParameters[0] = value0;
  7378. this._blendFunctionParameters[1] = value1;
  7379. this._blendFunctionParameters[2] = value2;
  7380. this._blendFunctionParameters[3] = value3;
  7381. this._isBlendFunctionParametersDirty = true;
  7382. };
  7383. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  7384. if (this._blendEquationParameters[0] === rgb &&
  7385. this._blendEquationParameters[1] === alpha) {
  7386. return;
  7387. }
  7388. this._blendEquationParameters[0] = rgb;
  7389. this._blendEquationParameters[1] = alpha;
  7390. this._isBlendEquationParametersDirty = true;
  7391. };
  7392. _AlphaState.prototype.reset = function () {
  7393. this._alphaBlend = false;
  7394. this._blendFunctionParameters[0] = null;
  7395. this._blendFunctionParameters[1] = null;
  7396. this._blendFunctionParameters[2] = null;
  7397. this._blendFunctionParameters[3] = null;
  7398. this._blendEquationParameters[0] = null;
  7399. this._blendEquationParameters[1] = null;
  7400. this._blendConstants[0] = null;
  7401. this._blendConstants[1] = null;
  7402. this._blendConstants[2] = null;
  7403. this._blendConstants[3] = null;
  7404. this._isAlphaBlendDirty = true;
  7405. this._isBlendFunctionParametersDirty = false;
  7406. this._isBlendEquationParametersDirty = false;
  7407. this._isBlendConstantsDirty = false;
  7408. };
  7409. _AlphaState.prototype.apply = function (gl) {
  7410. if (!this.isDirty) {
  7411. return;
  7412. }
  7413. // Alpha blend
  7414. if (this._isAlphaBlendDirty) {
  7415. if (this._alphaBlend) {
  7416. gl.enable(gl.BLEND);
  7417. }
  7418. else {
  7419. gl.disable(gl.BLEND);
  7420. }
  7421. this._isAlphaBlendDirty = false;
  7422. }
  7423. // Alpha function
  7424. if (this._isBlendFunctionParametersDirty) {
  7425. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  7426. this._isBlendFunctionParametersDirty = false;
  7427. }
  7428. // Alpha equation
  7429. if (this._isBlendEquationParametersDirty) {
  7430. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  7431. this._isBlendEquationParametersDirty = false;
  7432. }
  7433. // Constants
  7434. if (this._isBlendConstantsDirty) {
  7435. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  7436. this._isBlendConstantsDirty = false;
  7437. }
  7438. };
  7439. return _AlphaState;
  7440. }());
  7441. Internals._AlphaState = _AlphaState;
  7442. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7443. })(BABYLON || (BABYLON = {}));
  7444. //# sourceMappingURL=babylon.alphaCullingState.js.map
  7445. var BABYLON;
  7446. (function (BABYLON) {
  7447. var Internals;
  7448. (function (Internals) {
  7449. var _DepthCullingState = /** @class */ (function () {
  7450. /**
  7451. * Initializes the state.
  7452. */
  7453. function _DepthCullingState() {
  7454. this._isDepthTestDirty = false;
  7455. this._isDepthMaskDirty = false;
  7456. this._isDepthFuncDirty = false;
  7457. this._isCullFaceDirty = false;
  7458. this._isCullDirty = false;
  7459. this._isZOffsetDirty = false;
  7460. this._isFrontFaceDirty = false;
  7461. this.reset();
  7462. }
  7463. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  7464. get: function () {
  7465. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  7466. },
  7467. enumerable: true,
  7468. configurable: true
  7469. });
  7470. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  7471. get: function () {
  7472. return this._zOffset;
  7473. },
  7474. set: function (value) {
  7475. if (this._zOffset === value) {
  7476. return;
  7477. }
  7478. this._zOffset = value;
  7479. this._isZOffsetDirty = true;
  7480. },
  7481. enumerable: true,
  7482. configurable: true
  7483. });
  7484. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  7485. get: function () {
  7486. return this._cullFace;
  7487. },
  7488. set: function (value) {
  7489. if (this._cullFace === value) {
  7490. return;
  7491. }
  7492. this._cullFace = value;
  7493. this._isCullFaceDirty = true;
  7494. },
  7495. enumerable: true,
  7496. configurable: true
  7497. });
  7498. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  7499. get: function () {
  7500. return this._cull;
  7501. },
  7502. set: function (value) {
  7503. if (this._cull === value) {
  7504. return;
  7505. }
  7506. this._cull = value;
  7507. this._isCullDirty = true;
  7508. },
  7509. enumerable: true,
  7510. configurable: true
  7511. });
  7512. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  7513. get: function () {
  7514. return this._depthFunc;
  7515. },
  7516. set: function (value) {
  7517. if (this._depthFunc === value) {
  7518. return;
  7519. }
  7520. this._depthFunc = value;
  7521. this._isDepthFuncDirty = true;
  7522. },
  7523. enumerable: true,
  7524. configurable: true
  7525. });
  7526. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  7527. get: function () {
  7528. return this._depthMask;
  7529. },
  7530. set: function (value) {
  7531. if (this._depthMask === value) {
  7532. return;
  7533. }
  7534. this._depthMask = value;
  7535. this._isDepthMaskDirty = true;
  7536. },
  7537. enumerable: true,
  7538. configurable: true
  7539. });
  7540. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  7541. get: function () {
  7542. return this._depthTest;
  7543. },
  7544. set: function (value) {
  7545. if (this._depthTest === value) {
  7546. return;
  7547. }
  7548. this._depthTest = value;
  7549. this._isDepthTestDirty = true;
  7550. },
  7551. enumerable: true,
  7552. configurable: true
  7553. });
  7554. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  7555. get: function () {
  7556. return this._frontFace;
  7557. },
  7558. set: function (value) {
  7559. if (this._frontFace === value) {
  7560. return;
  7561. }
  7562. this._frontFace = value;
  7563. this._isFrontFaceDirty = true;
  7564. },
  7565. enumerable: true,
  7566. configurable: true
  7567. });
  7568. _DepthCullingState.prototype.reset = function () {
  7569. this._depthMask = true;
  7570. this._depthTest = true;
  7571. this._depthFunc = null;
  7572. this._cullFace = null;
  7573. this._cull = null;
  7574. this._zOffset = 0;
  7575. this._frontFace = null;
  7576. this._isDepthTestDirty = true;
  7577. this._isDepthMaskDirty = true;
  7578. this._isDepthFuncDirty = false;
  7579. this._isCullFaceDirty = false;
  7580. this._isCullDirty = false;
  7581. this._isZOffsetDirty = false;
  7582. this._isFrontFaceDirty = false;
  7583. };
  7584. _DepthCullingState.prototype.apply = function (gl) {
  7585. if (!this.isDirty) {
  7586. return;
  7587. }
  7588. // Cull
  7589. if (this._isCullDirty) {
  7590. if (this.cull) {
  7591. gl.enable(gl.CULL_FACE);
  7592. }
  7593. else {
  7594. gl.disable(gl.CULL_FACE);
  7595. }
  7596. this._isCullDirty = false;
  7597. }
  7598. // Cull face
  7599. if (this._isCullFaceDirty) {
  7600. gl.cullFace(this.cullFace);
  7601. this._isCullFaceDirty = false;
  7602. }
  7603. // Depth mask
  7604. if (this._isDepthMaskDirty) {
  7605. gl.depthMask(this.depthMask);
  7606. this._isDepthMaskDirty = false;
  7607. }
  7608. // Depth test
  7609. if (this._isDepthTestDirty) {
  7610. if (this.depthTest) {
  7611. gl.enable(gl.DEPTH_TEST);
  7612. }
  7613. else {
  7614. gl.disable(gl.DEPTH_TEST);
  7615. }
  7616. this._isDepthTestDirty = false;
  7617. }
  7618. // Depth func
  7619. if (this._isDepthFuncDirty) {
  7620. gl.depthFunc(this.depthFunc);
  7621. this._isDepthFuncDirty = false;
  7622. }
  7623. // zOffset
  7624. if (this._isZOffsetDirty) {
  7625. if (this.zOffset) {
  7626. gl.enable(gl.POLYGON_OFFSET_FILL);
  7627. gl.polygonOffset(this.zOffset, 0);
  7628. }
  7629. else {
  7630. gl.disable(gl.POLYGON_OFFSET_FILL);
  7631. }
  7632. this._isZOffsetDirty = false;
  7633. }
  7634. // Front face
  7635. if (this._isFrontFaceDirty) {
  7636. gl.frontFace(this.frontFace);
  7637. this._isFrontFaceDirty = false;
  7638. }
  7639. };
  7640. return _DepthCullingState;
  7641. }());
  7642. Internals._DepthCullingState = _DepthCullingState;
  7643. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7644. })(BABYLON || (BABYLON = {}));
  7645. //# sourceMappingURL=babylon.depthCullingState.js.map
  7646. var BABYLON;
  7647. (function (BABYLON) {
  7648. var Internals;
  7649. (function (Internals) {
  7650. var _StencilState = /** @class */ (function () {
  7651. function _StencilState() {
  7652. this._isStencilTestDirty = false;
  7653. this._isStencilMaskDirty = false;
  7654. this._isStencilFuncDirty = false;
  7655. this._isStencilOpDirty = false;
  7656. this.reset();
  7657. }
  7658. Object.defineProperty(_StencilState.prototype, "isDirty", {
  7659. get: function () {
  7660. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  7661. },
  7662. enumerable: true,
  7663. configurable: true
  7664. });
  7665. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  7666. get: function () {
  7667. return this._stencilFunc;
  7668. },
  7669. set: function (value) {
  7670. if (this._stencilFunc === value) {
  7671. return;
  7672. }
  7673. this._stencilFunc = value;
  7674. this._isStencilFuncDirty = true;
  7675. },
  7676. enumerable: true,
  7677. configurable: true
  7678. });
  7679. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  7680. get: function () {
  7681. return this._stencilFuncRef;
  7682. },
  7683. set: function (value) {
  7684. if (this._stencilFuncRef === value) {
  7685. return;
  7686. }
  7687. this._stencilFuncRef = value;
  7688. this._isStencilFuncDirty = true;
  7689. },
  7690. enumerable: true,
  7691. configurable: true
  7692. });
  7693. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  7694. get: function () {
  7695. return this._stencilFuncMask;
  7696. },
  7697. set: function (value) {
  7698. if (this._stencilFuncMask === value) {
  7699. return;
  7700. }
  7701. this._stencilFuncMask = value;
  7702. this._isStencilFuncDirty = true;
  7703. },
  7704. enumerable: true,
  7705. configurable: true
  7706. });
  7707. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  7708. get: function () {
  7709. return this._stencilOpStencilFail;
  7710. },
  7711. set: function (value) {
  7712. if (this._stencilOpStencilFail === value) {
  7713. return;
  7714. }
  7715. this._stencilOpStencilFail = value;
  7716. this._isStencilOpDirty = true;
  7717. },
  7718. enumerable: true,
  7719. configurable: true
  7720. });
  7721. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  7722. get: function () {
  7723. return this._stencilOpDepthFail;
  7724. },
  7725. set: function (value) {
  7726. if (this._stencilOpDepthFail === value) {
  7727. return;
  7728. }
  7729. this._stencilOpDepthFail = value;
  7730. this._isStencilOpDirty = true;
  7731. },
  7732. enumerable: true,
  7733. configurable: true
  7734. });
  7735. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  7736. get: function () {
  7737. return this._stencilOpStencilDepthPass;
  7738. },
  7739. set: function (value) {
  7740. if (this._stencilOpStencilDepthPass === value) {
  7741. return;
  7742. }
  7743. this._stencilOpStencilDepthPass = value;
  7744. this._isStencilOpDirty = true;
  7745. },
  7746. enumerable: true,
  7747. configurable: true
  7748. });
  7749. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  7750. get: function () {
  7751. return this._stencilMask;
  7752. },
  7753. set: function (value) {
  7754. if (this._stencilMask === value) {
  7755. return;
  7756. }
  7757. this._stencilMask = value;
  7758. this._isStencilMaskDirty = true;
  7759. },
  7760. enumerable: true,
  7761. configurable: true
  7762. });
  7763. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  7764. get: function () {
  7765. return this._stencilTest;
  7766. },
  7767. set: function (value) {
  7768. if (this._stencilTest === value) {
  7769. return;
  7770. }
  7771. this._stencilTest = value;
  7772. this._isStencilTestDirty = true;
  7773. },
  7774. enumerable: true,
  7775. configurable: true
  7776. });
  7777. _StencilState.prototype.reset = function () {
  7778. this._stencilTest = false;
  7779. this._stencilMask = 0xFF;
  7780. this._stencilFunc = BABYLON.Engine.ALWAYS;
  7781. this._stencilFuncRef = 1;
  7782. this._stencilFuncMask = 0xFF;
  7783. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  7784. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  7785. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  7786. this._isStencilTestDirty = true;
  7787. this._isStencilMaskDirty = true;
  7788. this._isStencilFuncDirty = true;
  7789. this._isStencilOpDirty = true;
  7790. };
  7791. _StencilState.prototype.apply = function (gl) {
  7792. if (!this.isDirty) {
  7793. return;
  7794. }
  7795. // Stencil test
  7796. if (this._isStencilTestDirty) {
  7797. if (this.stencilTest) {
  7798. gl.enable(gl.STENCIL_TEST);
  7799. }
  7800. else {
  7801. gl.disable(gl.STENCIL_TEST);
  7802. }
  7803. this._isStencilTestDirty = false;
  7804. }
  7805. // Stencil mask
  7806. if (this._isStencilMaskDirty) {
  7807. gl.stencilMask(this.stencilMask);
  7808. this._isStencilMaskDirty = false;
  7809. }
  7810. // Stencil func
  7811. if (this._isStencilFuncDirty) {
  7812. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  7813. this._isStencilFuncDirty = false;
  7814. }
  7815. // Stencil op
  7816. if (this._isStencilOpDirty) {
  7817. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  7818. this._isStencilOpDirty = false;
  7819. }
  7820. };
  7821. return _StencilState;
  7822. }());
  7823. Internals._StencilState = _StencilState;
  7824. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7825. })(BABYLON || (BABYLON = {}));
  7826. //# sourceMappingURL=babylon.stencilState.js.map
  7827. var BABYLON;
  7828. (function (BABYLON) {
  7829. var compileShader = function (gl, source, type, defines, shaderVersion) {
  7830. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  7831. };
  7832. var compileRawShader = function (gl, source, type) {
  7833. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  7834. gl.shaderSource(shader, source);
  7835. gl.compileShader(shader);
  7836. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  7837. var log = gl.getShaderInfoLog(shader);
  7838. if (log) {
  7839. throw new Error(log);
  7840. }
  7841. }
  7842. if (!shader) {
  7843. throw new Error("Something went wrong while compile the shader.");
  7844. }
  7845. return shader;
  7846. };
  7847. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  7848. var magFilter = gl.NEAREST;
  7849. var minFilter = gl.NEAREST;
  7850. switch (samplingMode) {
  7851. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  7852. magFilter = gl.LINEAR;
  7853. if (generateMipMaps) {
  7854. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  7855. }
  7856. else {
  7857. minFilter = gl.LINEAR;
  7858. }
  7859. break;
  7860. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  7861. magFilter = gl.LINEAR;
  7862. if (generateMipMaps) {
  7863. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7864. }
  7865. else {
  7866. minFilter = gl.LINEAR;
  7867. }
  7868. break;
  7869. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  7870. magFilter = gl.NEAREST;
  7871. if (generateMipMaps) {
  7872. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  7873. }
  7874. else {
  7875. minFilter = gl.NEAREST;
  7876. }
  7877. break;
  7878. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  7879. magFilter = gl.NEAREST;
  7880. if (generateMipMaps) {
  7881. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  7882. }
  7883. else {
  7884. minFilter = gl.NEAREST;
  7885. }
  7886. break;
  7887. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  7888. magFilter = gl.NEAREST;
  7889. if (generateMipMaps) {
  7890. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  7891. }
  7892. else {
  7893. minFilter = gl.LINEAR;
  7894. }
  7895. break;
  7896. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  7897. magFilter = gl.NEAREST;
  7898. if (generateMipMaps) {
  7899. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7900. }
  7901. else {
  7902. minFilter = gl.LINEAR;
  7903. }
  7904. break;
  7905. case BABYLON.Texture.NEAREST_LINEAR:
  7906. magFilter = gl.NEAREST;
  7907. minFilter = gl.LINEAR;
  7908. break;
  7909. case BABYLON.Texture.NEAREST_NEAREST:
  7910. magFilter = gl.NEAREST;
  7911. minFilter = gl.NEAREST;
  7912. break;
  7913. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  7914. magFilter = gl.LINEAR;
  7915. if (generateMipMaps) {
  7916. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  7917. }
  7918. else {
  7919. minFilter = gl.NEAREST;
  7920. }
  7921. break;
  7922. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  7923. magFilter = gl.LINEAR;
  7924. if (generateMipMaps) {
  7925. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  7926. }
  7927. else {
  7928. minFilter = gl.NEAREST;
  7929. }
  7930. break;
  7931. case BABYLON.Texture.LINEAR_LINEAR:
  7932. magFilter = gl.LINEAR;
  7933. minFilter = gl.LINEAR;
  7934. break;
  7935. case BABYLON.Texture.LINEAR_NEAREST:
  7936. magFilter = gl.LINEAR;
  7937. minFilter = gl.NEAREST;
  7938. break;
  7939. }
  7940. return {
  7941. min: minFilter,
  7942. mag: magFilter
  7943. };
  7944. };
  7945. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  7946. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  7947. var img;
  7948. var onload = function () {
  7949. loadedImages[index] = img;
  7950. loadedImages._internalCount++;
  7951. if (scene) {
  7952. scene._removePendingData(img);
  7953. }
  7954. if (loadedImages._internalCount === 6) {
  7955. onfinish(loadedImages);
  7956. }
  7957. };
  7958. var onerror = function (message, exception) {
  7959. if (scene) {
  7960. scene._removePendingData(img);
  7961. }
  7962. if (onErrorCallBack) {
  7963. onErrorCallBack(message, exception);
  7964. }
  7965. };
  7966. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  7967. if (scene) {
  7968. scene._addPendingData(img);
  7969. }
  7970. };
  7971. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  7972. if (onError === void 0) { onError = null; }
  7973. var loadedImages = [];
  7974. loadedImages._internalCount = 0;
  7975. for (var index = 0; index < 6; index++) {
  7976. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  7977. }
  7978. };
  7979. var BufferPointer = /** @class */ (function () {
  7980. function BufferPointer() {
  7981. }
  7982. return BufferPointer;
  7983. }());
  7984. var InstancingAttributeInfo = /** @class */ (function () {
  7985. function InstancingAttributeInfo() {
  7986. }
  7987. return InstancingAttributeInfo;
  7988. }());
  7989. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  7990. /**
  7991. * Define options used to create a render target texture
  7992. */
  7993. var RenderTargetCreationOptions = /** @class */ (function () {
  7994. function RenderTargetCreationOptions() {
  7995. }
  7996. return RenderTargetCreationOptions;
  7997. }());
  7998. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  7999. /**
  8000. * Regroup several parameters relative to the browser in use
  8001. */
  8002. var EngineCapabilities = /** @class */ (function () {
  8003. function EngineCapabilities() {
  8004. }
  8005. return EngineCapabilities;
  8006. }());
  8007. BABYLON.EngineCapabilities = EngineCapabilities;
  8008. /**
  8009. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  8010. */
  8011. var Engine = /** @class */ (function () {
  8012. /**
  8013. * @constructor
  8014. * @param {HTMLCanvasElement | WebGLRenderingContext} canvasOrContext - the canvas or the webgl context to be used for rendering
  8015. * @param {boolean} [antialias] - enable antialias
  8016. * @param options - further options to be sent to the getContext function
  8017. */
  8018. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  8019. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  8020. var _this = this;
  8021. // Public members
  8022. this.forcePOTTextures = false;
  8023. this.isFullscreen = false;
  8024. this.isPointerLock = false;
  8025. this.cullBackFaces = true;
  8026. this.renderEvenInBackground = true;
  8027. this.preventCacheWipeBetweenFrames = false;
  8028. // To enable/disable IDB support and avoid XHR on .manifest
  8029. this.enableOfflineSupport = false;
  8030. this.scenes = new Array();
  8031. this.postProcesses = new Array();
  8032. // Observables
  8033. /**
  8034. * Observable event triggered each time the rendering canvas is resized
  8035. */
  8036. this.onResizeObservable = new BABYLON.Observable();
  8037. /**
  8038. * Observable event triggered each time the canvas loses focus
  8039. */
  8040. this.onCanvasBlurObservable = new BABYLON.Observable();
  8041. /**
  8042. * Observable event triggered each time the canvas gains focus
  8043. */
  8044. this.onCanvasFocusObservable = new BABYLON.Observable();
  8045. /**
  8046. * Observable event triggered each time the canvas receives pointerout event
  8047. */
  8048. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  8049. /**
  8050. * Observable event triggered before each texture is initialized
  8051. */
  8052. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  8053. //WebVR
  8054. this._vrDisplay = undefined;
  8055. this._vrSupported = false;
  8056. this._vrExclusivePointerMode = false;
  8057. // Uniform buffers list
  8058. this.disableUniformBuffers = false;
  8059. this._uniformBuffers = new Array();
  8060. // Observables
  8061. /**
  8062. * Observable raised when the engine begins a new frame
  8063. */
  8064. this.onBeginFrameObservable = new BABYLON.Observable();
  8065. /**
  8066. * Observable raised when the engine ends the current frame
  8067. */
  8068. this.onEndFrameObservable = new BABYLON.Observable();
  8069. /**
  8070. * Observable raised when the engine is about to compile a shader
  8071. */
  8072. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  8073. /**
  8074. * Observable raised when the engine has jsut compiled a shader
  8075. */
  8076. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  8077. this._windowIsBackground = false;
  8078. this._webGLVersion = 1.0;
  8079. this._badOS = false;
  8080. this._badDesktopOS = false;
  8081. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  8082. this.onVRRequestPresentComplete = new BABYLON.Observable();
  8083. this.onVRRequestPresentStart = new BABYLON.Observable();
  8084. this._colorWrite = true;
  8085. this._drawCalls = new BABYLON.PerfCounter();
  8086. this._textureCollisions = new BABYLON.PerfCounter();
  8087. this._renderingQueueLaunched = false;
  8088. this._activeRenderLoops = new Array();
  8089. // Deterministic lockstepMaxSteps
  8090. this._deterministicLockstep = false;
  8091. this._lockstepMaxSteps = 4;
  8092. // Lost context
  8093. this.onContextLostObservable = new BABYLON.Observable();
  8094. this.onContextRestoredObservable = new BABYLON.Observable();
  8095. this._contextWasLost = false;
  8096. this._doNotHandleContextLost = false;
  8097. // FPS
  8098. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  8099. this._fps = 60;
  8100. this._deltaTime = 0;
  8101. /**
  8102. * Turn this value on if you want to pause FPS computation when in background
  8103. */
  8104. this.disablePerformanceMonitorInBackground = false;
  8105. // States
  8106. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  8107. this._stencilState = new BABYLON.Internals._StencilState();
  8108. this._alphaState = new BABYLON.Internals._AlphaState();
  8109. this._alphaMode = Engine.ALPHA_DISABLE;
  8110. // Cache
  8111. this._internalTexturesCache = new Array();
  8112. this._boundTexturesCache = {};
  8113. this._boundTexturesStack = new Array();
  8114. this._compiledEffects = {};
  8115. this._vertexAttribArraysEnabled = [];
  8116. this._uintIndicesCurrentlySet = false;
  8117. this._currentBoundBuffer = new Array();
  8118. this._currentBufferPointers = new Array();
  8119. this._currentInstanceLocations = new Array();
  8120. this._currentInstanceBuffers = new Array();
  8121. this._vaoRecordInProgress = false;
  8122. this._mustWipeVertexAttributes = false;
  8123. this._nextFreeTextureSlots = new Array();
  8124. this._activeRequests = new Array();
  8125. // Hardware supported Compressed Textures
  8126. this._texturesSupported = new Array();
  8127. this._onVRFullScreenTriggered = function () {
  8128. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  8129. //get the old size before we change
  8130. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  8131. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  8132. //get the width and height, change the render size
  8133. var leftEye = _this._vrDisplay.getEyeParameters('left');
  8134. _this.setHardwareScalingLevel(1);
  8135. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  8136. }
  8137. else {
  8138. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  8139. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  8140. }
  8141. };
  8142. this._boundUniforms = {};
  8143. var canvas = null;
  8144. Engine.Instances.push(this);
  8145. if (!canvasOrContext) {
  8146. return;
  8147. }
  8148. options = options || {};
  8149. if (canvasOrContext.getContext) {
  8150. canvas = canvasOrContext;
  8151. this._renderingCanvas = canvas;
  8152. if (antialias != null) {
  8153. options.antialias = antialias;
  8154. }
  8155. if (options.deterministicLockstep === undefined) {
  8156. options.deterministicLockstep = false;
  8157. }
  8158. if (options.lockstepMaxSteps === undefined) {
  8159. options.lockstepMaxSteps = 4;
  8160. }
  8161. if (options.preserveDrawingBuffer === undefined) {
  8162. options.preserveDrawingBuffer = false;
  8163. }
  8164. if (options.audioEngine === undefined) {
  8165. options.audioEngine = true;
  8166. }
  8167. if (options.stencil === undefined) {
  8168. options.stencil = true;
  8169. }
  8170. this._deterministicLockstep = options.deterministicLockstep;
  8171. this._lockstepMaxSteps = options.lockstepMaxSteps;
  8172. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  8173. // Exceptions
  8174. if (!options.disableWebGL2Support) {
  8175. if (navigator && navigator.userAgent) {
  8176. var ua = navigator.userAgent;
  8177. for (var _i = 0, _a = Engine.WebGL2UniformBuffersExceptionList; _i < _a.length; _i++) {
  8178. var exception = _a[_i];
  8179. if (ua.indexOf(exception) > -1) {
  8180. this.disableUniformBuffers = true;
  8181. console.log("TODO remove this!! this.disableUniformBuffers set to true!!!!");
  8182. break;
  8183. }
  8184. }
  8185. }
  8186. }
  8187. // GL
  8188. if (!options.disableWebGL2Support) {
  8189. try {
  8190. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  8191. if (this._gl) {
  8192. this._webGLVersion = 2.0;
  8193. }
  8194. }
  8195. catch (e) {
  8196. // Do nothing
  8197. }
  8198. }
  8199. if (!this._gl) {
  8200. if (!canvas) {
  8201. throw new Error("The provided canvas is null or undefined.");
  8202. }
  8203. try {
  8204. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  8205. }
  8206. catch (e) {
  8207. throw new Error("WebGL not supported");
  8208. }
  8209. }
  8210. if (!this._gl) {
  8211. throw new Error("WebGL not supported");
  8212. }
  8213. this._onCanvasFocus = function () {
  8214. _this.onCanvasFocusObservable.notifyObservers(_this);
  8215. };
  8216. this._onCanvasBlur = function () {
  8217. _this.onCanvasBlurObservable.notifyObservers(_this);
  8218. };
  8219. canvas.addEventListener("focus", this._onCanvasFocus);
  8220. canvas.addEventListener("blur", this._onCanvasBlur);
  8221. this._onBlur = function () {
  8222. if (_this.disablePerformanceMonitorInBackground) {
  8223. _this._performanceMonitor.disable();
  8224. }
  8225. _this._windowIsBackground = true;
  8226. };
  8227. this._onFocus = function () {
  8228. if (_this.disablePerformanceMonitorInBackground) {
  8229. _this._performanceMonitor.enable();
  8230. }
  8231. _this._windowIsBackground = false;
  8232. };
  8233. this._onCanvasPointerOut = function () {
  8234. _this.onCanvasPointerOutObservable.notifyObservers(_this);
  8235. };
  8236. window.addEventListener("blur", this._onBlur);
  8237. window.addEventListener("focus", this._onFocus);
  8238. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  8239. // Context lost
  8240. if (!this._doNotHandleContextLost) {
  8241. this._onContextLost = function (evt) {
  8242. evt.preventDefault();
  8243. _this._contextWasLost = true;
  8244. BABYLON.Tools.Warn("WebGL context lost.");
  8245. _this.onContextLostObservable.notifyObservers(_this);
  8246. };
  8247. this._onContextRestored = function (evt) {
  8248. // Adding a timeout to avoid race condition at browser level
  8249. setTimeout(function () {
  8250. // Rebuild gl context
  8251. _this._initGLContext();
  8252. // Rebuild effects
  8253. _this._rebuildEffects();
  8254. // Rebuild textures
  8255. _this._rebuildInternalTextures();
  8256. // Rebuild buffers
  8257. _this._rebuildBuffers();
  8258. // Cache
  8259. _this.wipeCaches(true);
  8260. BABYLON.Tools.Warn("WebGL context successfully restored.");
  8261. _this.onContextRestoredObservable.notifyObservers(_this);
  8262. _this._contextWasLost = false;
  8263. }, 0);
  8264. };
  8265. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  8266. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  8267. }
  8268. }
  8269. else {
  8270. this._gl = canvasOrContext;
  8271. this._renderingCanvas = this._gl.canvas;
  8272. if (this._gl.renderbufferStorageMultisample) {
  8273. this._webGLVersion = 2.0;
  8274. }
  8275. options.stencil = this._gl.getContextAttributes().stencil;
  8276. }
  8277. // Viewport
  8278. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  8279. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  8280. this.resize();
  8281. this._isStencilEnable = options.stencil ? true : false;
  8282. this._initGLContext();
  8283. if (canvas) {
  8284. // Fullscreen
  8285. this._onFullscreenChange = function () {
  8286. if (document.fullscreen !== undefined) {
  8287. _this.isFullscreen = document.fullscreen;
  8288. }
  8289. else if (document.mozFullScreen !== undefined) {
  8290. _this.isFullscreen = document.mozFullScreen;
  8291. }
  8292. else if (document.webkitIsFullScreen !== undefined) {
  8293. _this.isFullscreen = document.webkitIsFullScreen;
  8294. }
  8295. else if (document.msIsFullScreen !== undefined) {
  8296. _this.isFullscreen = document.msIsFullScreen;
  8297. }
  8298. // Pointer lock
  8299. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  8300. canvas.requestPointerLock = canvas.requestPointerLock ||
  8301. canvas.msRequestPointerLock ||
  8302. canvas.mozRequestPointerLock ||
  8303. canvas.webkitRequestPointerLock;
  8304. if (canvas.requestPointerLock) {
  8305. canvas.requestPointerLock();
  8306. }
  8307. }
  8308. };
  8309. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  8310. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  8311. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  8312. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  8313. // Pointer lock
  8314. this._onPointerLockChange = function () {
  8315. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  8316. document.webkitPointerLockElement === canvas ||
  8317. document.msPointerLockElement === canvas ||
  8318. document.pointerLockElement === canvas);
  8319. };
  8320. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  8321. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  8322. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  8323. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  8324. this._onVRDisplayPointerRestricted = function () {
  8325. if (canvas) {
  8326. canvas.requestPointerLock();
  8327. }
  8328. };
  8329. this._onVRDisplayPointerUnrestricted = function () {
  8330. document.exitPointerLock();
  8331. };
  8332. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  8333. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  8334. }
  8335. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  8336. Engine.audioEngine = new BABYLON.AudioEngine();
  8337. }
  8338. // Prepare buffer pointers
  8339. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  8340. this._currentBufferPointers[i] = new BufferPointer();
  8341. }
  8342. // Load WebVR Devices
  8343. if (options.autoEnableWebVR) {
  8344. this.initWebVR();
  8345. }
  8346. // Detect if we are running on a faulty buggy OS.
  8347. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  8348. // Detect if we are running on a faulty buggy desktop OS.
  8349. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  8350. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  8351. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  8352. }
  8353. Object.defineProperty(Engine, "LastCreatedEngine", {
  8354. get: function () {
  8355. if (Engine.Instances.length === 0) {
  8356. return null;
  8357. }
  8358. return Engine.Instances[Engine.Instances.length - 1];
  8359. },
  8360. enumerable: true,
  8361. configurable: true
  8362. });
  8363. Object.defineProperty(Engine, "LastCreatedScene", {
  8364. get: function () {
  8365. var lastCreatedEngine = Engine.LastCreatedEngine;
  8366. if (!lastCreatedEngine) {
  8367. return null;
  8368. }
  8369. if (lastCreatedEngine.scenes.length === 0) {
  8370. return null;
  8371. }
  8372. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  8373. },
  8374. enumerable: true,
  8375. configurable: true
  8376. });
  8377. /**
  8378. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  8379. */
  8380. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  8381. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  8382. var engine = Engine.Instances[engineIndex];
  8383. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  8384. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  8385. }
  8386. }
  8387. };
  8388. Object.defineProperty(Engine, "NEVER", {
  8389. get: function () {
  8390. return Engine._NEVER;
  8391. },
  8392. enumerable: true,
  8393. configurable: true
  8394. });
  8395. Object.defineProperty(Engine, "ALWAYS", {
  8396. get: function () {
  8397. return Engine._ALWAYS;
  8398. },
  8399. enumerable: true,
  8400. configurable: true
  8401. });
  8402. Object.defineProperty(Engine, "LESS", {
  8403. get: function () {
  8404. return Engine._LESS;
  8405. },
  8406. enumerable: true,
  8407. configurable: true
  8408. });
  8409. Object.defineProperty(Engine, "EQUAL", {
  8410. get: function () {
  8411. return Engine._EQUAL;
  8412. },
  8413. enumerable: true,
  8414. configurable: true
  8415. });
  8416. Object.defineProperty(Engine, "LEQUAL", {
  8417. get: function () {
  8418. return Engine._LEQUAL;
  8419. },
  8420. enumerable: true,
  8421. configurable: true
  8422. });
  8423. Object.defineProperty(Engine, "GREATER", {
  8424. get: function () {
  8425. return Engine._GREATER;
  8426. },
  8427. enumerable: true,
  8428. configurable: true
  8429. });
  8430. Object.defineProperty(Engine, "GEQUAL", {
  8431. get: function () {
  8432. return Engine._GEQUAL;
  8433. },
  8434. enumerable: true,
  8435. configurable: true
  8436. });
  8437. Object.defineProperty(Engine, "NOTEQUAL", {
  8438. get: function () {
  8439. return Engine._NOTEQUAL;
  8440. },
  8441. enumerable: true,
  8442. configurable: true
  8443. });
  8444. Object.defineProperty(Engine, "KEEP", {
  8445. get: function () {
  8446. return Engine._KEEP;
  8447. },
  8448. enumerable: true,
  8449. configurable: true
  8450. });
  8451. Object.defineProperty(Engine, "REPLACE", {
  8452. get: function () {
  8453. return Engine._REPLACE;
  8454. },
  8455. enumerable: true,
  8456. configurable: true
  8457. });
  8458. Object.defineProperty(Engine, "INCR", {
  8459. get: function () {
  8460. return Engine._INCR;
  8461. },
  8462. enumerable: true,
  8463. configurable: true
  8464. });
  8465. Object.defineProperty(Engine, "DECR", {
  8466. get: function () {
  8467. return Engine._DECR;
  8468. },
  8469. enumerable: true,
  8470. configurable: true
  8471. });
  8472. Object.defineProperty(Engine, "INVERT", {
  8473. get: function () {
  8474. return Engine._INVERT;
  8475. },
  8476. enumerable: true,
  8477. configurable: true
  8478. });
  8479. Object.defineProperty(Engine, "INCR_WRAP", {
  8480. get: function () {
  8481. return Engine._INCR_WRAP;
  8482. },
  8483. enumerable: true,
  8484. configurable: true
  8485. });
  8486. Object.defineProperty(Engine, "DECR_WRAP", {
  8487. get: function () {
  8488. return Engine._DECR_WRAP;
  8489. },
  8490. enumerable: true,
  8491. configurable: true
  8492. });
  8493. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  8494. get: function () {
  8495. return Engine._ALPHA_DISABLE;
  8496. },
  8497. enumerable: true,
  8498. configurable: true
  8499. });
  8500. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  8501. get: function () {
  8502. return Engine._ALPHA_ONEONE;
  8503. },
  8504. enumerable: true,
  8505. configurable: true
  8506. });
  8507. Object.defineProperty(Engine, "ALPHA_ADD", {
  8508. get: function () {
  8509. return Engine._ALPHA_ADD;
  8510. },
  8511. enumerable: true,
  8512. configurable: true
  8513. });
  8514. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  8515. get: function () {
  8516. return Engine._ALPHA_COMBINE;
  8517. },
  8518. enumerable: true,
  8519. configurable: true
  8520. });
  8521. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  8522. get: function () {
  8523. return Engine._ALPHA_SUBTRACT;
  8524. },
  8525. enumerable: true,
  8526. configurable: true
  8527. });
  8528. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  8529. get: function () {
  8530. return Engine._ALPHA_MULTIPLY;
  8531. },
  8532. enumerable: true,
  8533. configurable: true
  8534. });
  8535. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  8536. get: function () {
  8537. return Engine._ALPHA_MAXIMIZED;
  8538. },
  8539. enumerable: true,
  8540. configurable: true
  8541. });
  8542. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  8543. get: function () {
  8544. return Engine._ALPHA_PREMULTIPLIED;
  8545. },
  8546. enumerable: true,
  8547. configurable: true
  8548. });
  8549. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  8550. get: function () {
  8551. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  8552. },
  8553. enumerable: true,
  8554. configurable: true
  8555. });
  8556. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  8557. get: function () {
  8558. return Engine._ALPHA_INTERPOLATE;
  8559. },
  8560. enumerable: true,
  8561. configurable: true
  8562. });
  8563. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  8564. get: function () {
  8565. return Engine._ALPHA_SCREENMODE;
  8566. },
  8567. enumerable: true,
  8568. configurable: true
  8569. });
  8570. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  8571. get: function () {
  8572. return Engine._DELAYLOADSTATE_NONE;
  8573. },
  8574. enumerable: true,
  8575. configurable: true
  8576. });
  8577. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  8578. get: function () {
  8579. return Engine._DELAYLOADSTATE_LOADED;
  8580. },
  8581. enumerable: true,
  8582. configurable: true
  8583. });
  8584. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  8585. get: function () {
  8586. return Engine._DELAYLOADSTATE_LOADING;
  8587. },
  8588. enumerable: true,
  8589. configurable: true
  8590. });
  8591. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  8592. get: function () {
  8593. return Engine._DELAYLOADSTATE_NOTLOADED;
  8594. },
  8595. enumerable: true,
  8596. configurable: true
  8597. });
  8598. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  8599. get: function () {
  8600. return Engine._TEXTUREFORMAT_ALPHA;
  8601. },
  8602. enumerable: true,
  8603. configurable: true
  8604. });
  8605. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  8606. get: function () {
  8607. return Engine._TEXTUREFORMAT_LUMINANCE;
  8608. },
  8609. enumerable: true,
  8610. configurable: true
  8611. });
  8612. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  8613. get: function () {
  8614. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  8615. },
  8616. enumerable: true,
  8617. configurable: true
  8618. });
  8619. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  8620. get: function () {
  8621. return Engine._TEXTUREFORMAT_RGB;
  8622. },
  8623. enumerable: true,
  8624. configurable: true
  8625. });
  8626. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  8627. get: function () {
  8628. return Engine._TEXTUREFORMAT_RGBA;
  8629. },
  8630. enumerable: true,
  8631. configurable: true
  8632. });
  8633. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  8634. get: function () {
  8635. return Engine._TEXTURETYPE_UNSIGNED_INT;
  8636. },
  8637. enumerable: true,
  8638. configurable: true
  8639. });
  8640. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  8641. get: function () {
  8642. return Engine._TEXTURETYPE_FLOAT;
  8643. },
  8644. enumerable: true,
  8645. configurable: true
  8646. });
  8647. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  8648. get: function () {
  8649. return Engine._TEXTURETYPE_HALF_FLOAT;
  8650. },
  8651. enumerable: true,
  8652. configurable: true
  8653. });
  8654. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  8655. get: function () {
  8656. return Engine._SCALEMODE_FLOOR;
  8657. },
  8658. enumerable: true,
  8659. configurable: true
  8660. });
  8661. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  8662. get: function () {
  8663. return Engine._SCALEMODE_NEAREST;
  8664. },
  8665. enumerable: true,
  8666. configurable: true
  8667. });
  8668. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  8669. get: function () {
  8670. return Engine._SCALEMODE_CEILING;
  8671. },
  8672. enumerable: true,
  8673. configurable: true
  8674. });
  8675. Object.defineProperty(Engine, "Version", {
  8676. get: function () {
  8677. return "3.2.0-alpha1";
  8678. },
  8679. enumerable: true,
  8680. configurable: true
  8681. });
  8682. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  8683. get: function () {
  8684. return this._vrExclusivePointerMode;
  8685. },
  8686. enumerable: true,
  8687. configurable: true
  8688. });
  8689. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  8690. get: function () {
  8691. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  8692. },
  8693. enumerable: true,
  8694. configurable: true
  8695. });
  8696. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  8697. get: function () {
  8698. return this._webGLVersion < 2 || this.forcePOTTextures;
  8699. },
  8700. enumerable: true,
  8701. configurable: true
  8702. });
  8703. Object.defineProperty(Engine.prototype, "badOS", {
  8704. get: function () {
  8705. return this._badOS;
  8706. },
  8707. enumerable: true,
  8708. configurable: true
  8709. });
  8710. Object.defineProperty(Engine.prototype, "badDesktopOS", {
  8711. get: function () {
  8712. return this._badDesktopOS;
  8713. },
  8714. enumerable: true,
  8715. configurable: true
  8716. });
  8717. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  8718. get: function () {
  8719. return this._performanceMonitor;
  8720. },
  8721. enumerable: true,
  8722. configurable: true
  8723. });
  8724. Object.defineProperty(Engine.prototype, "texturesSupported", {
  8725. get: function () {
  8726. return this._texturesSupported;
  8727. },
  8728. enumerable: true,
  8729. configurable: true
  8730. });
  8731. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  8732. get: function () {
  8733. return this._textureFormatInUse;
  8734. },
  8735. enumerable: true,
  8736. configurable: true
  8737. });
  8738. Object.defineProperty(Engine.prototype, "currentViewport", {
  8739. get: function () {
  8740. return this._cachedViewport;
  8741. },
  8742. enumerable: true,
  8743. configurable: true
  8744. });
  8745. Object.defineProperty(Engine.prototype, "emptyTexture", {
  8746. // Empty texture
  8747. get: function () {
  8748. if (!this._emptyTexture) {
  8749. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8750. }
  8751. return this._emptyTexture;
  8752. },
  8753. enumerable: true,
  8754. configurable: true
  8755. });
  8756. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  8757. get: function () {
  8758. if (!this._emptyTexture3D) {
  8759. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8760. }
  8761. return this._emptyTexture3D;
  8762. },
  8763. enumerable: true,
  8764. configurable: true
  8765. });
  8766. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  8767. get: function () {
  8768. if (!this._emptyCubeTexture) {
  8769. var faceData = new Uint8Array(4);
  8770. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  8771. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8772. }
  8773. return this._emptyCubeTexture;
  8774. },
  8775. enumerable: true,
  8776. configurable: true
  8777. });
  8778. Engine.prototype._rebuildInternalTextures = function () {
  8779. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  8780. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  8781. var internalTexture = currentState_1[_i];
  8782. internalTexture._rebuild();
  8783. }
  8784. };
  8785. Engine.prototype._rebuildEffects = function () {
  8786. for (var key in this._compiledEffects) {
  8787. var effect = this._compiledEffects[key];
  8788. effect._prepareEffect();
  8789. }
  8790. BABYLON.Effect.ResetCache();
  8791. };
  8792. Engine.prototype._rebuildBuffers = function () {
  8793. // Index / Vertex
  8794. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  8795. var scene = _a[_i];
  8796. scene.resetCachedMaterial();
  8797. scene._rebuildGeometries();
  8798. scene._rebuildTextures();
  8799. }
  8800. // Uniforms
  8801. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  8802. var uniformBuffer = _c[_b];
  8803. uniformBuffer._rebuild();
  8804. }
  8805. };
  8806. Engine.prototype._initGLContext = function () {
  8807. // Caps
  8808. this._caps = new EngineCapabilities();
  8809. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  8810. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  8811. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  8812. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  8813. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  8814. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  8815. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  8816. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  8817. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  8818. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  8819. // Infos
  8820. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  8821. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  8822. if (rendererInfo != null) {
  8823. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  8824. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  8825. }
  8826. if (!this._glVendor) {
  8827. this._glVendor = "Unknown vendor";
  8828. }
  8829. if (!this._glRenderer) {
  8830. this._glRenderer = "Unknown renderer";
  8831. }
  8832. // Constants
  8833. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  8834. if (this._gl.RGBA16F !== 0x881A) {
  8835. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  8836. }
  8837. if (this._gl.RGBA32F !== 0x8814) {
  8838. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  8839. }
  8840. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  8841. this._gl.DEPTH24_STENCIL8 = 35056;
  8842. }
  8843. // Extensions
  8844. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  8845. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  8846. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  8847. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  8848. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  8849. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  8850. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  8851. 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');
  8852. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  8853. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  8854. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  8855. this._caps.highPrecisionShaderSupported = true;
  8856. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  8857. if (this._caps.timerQuery) {
  8858. if (this._webGLVersion === 1) {
  8859. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  8860. }
  8861. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  8862. }
  8863. // Checks if some of the format renders first to allow the use of webgl inspector.
  8864. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  8865. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  8866. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  8867. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  8868. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  8869. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  8870. if (this._webGLVersion > 1) {
  8871. this._gl.HALF_FLOAT_OES = 0x140B;
  8872. }
  8873. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  8874. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  8875. // Draw buffers
  8876. if (this._webGLVersion > 1) {
  8877. this._caps.drawBuffersExtension = true;
  8878. }
  8879. else {
  8880. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  8881. if (drawBuffersExtension !== null) {
  8882. this._caps.drawBuffersExtension = true;
  8883. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  8884. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  8885. for (var i = 0; i < 16; i++) {
  8886. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  8887. }
  8888. }
  8889. else {
  8890. this._caps.drawBuffersExtension = false;
  8891. }
  8892. }
  8893. // Depth Texture
  8894. if (this._webGLVersion > 1) {
  8895. this._caps.depthTextureExtension = true;
  8896. }
  8897. else {
  8898. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  8899. if (depthTextureExtension != null) {
  8900. this._caps.depthTextureExtension = true;
  8901. }
  8902. }
  8903. // Vertex array object
  8904. if (this._webGLVersion > 1) {
  8905. this._caps.vertexArrayObject = true;
  8906. }
  8907. else {
  8908. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  8909. if (vertexArrayObjectExtension != null) {
  8910. this._caps.vertexArrayObject = true;
  8911. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  8912. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  8913. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  8914. }
  8915. else {
  8916. this._caps.vertexArrayObject = false;
  8917. }
  8918. }
  8919. // Instances count
  8920. if (this._webGLVersion > 1) {
  8921. this._caps.instancedArrays = true;
  8922. }
  8923. else {
  8924. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  8925. if (instanceExtension != null) {
  8926. this._caps.instancedArrays = true;
  8927. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  8928. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  8929. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  8930. }
  8931. else {
  8932. this._caps.instancedArrays = false;
  8933. }
  8934. }
  8935. // Intelligently add supported compressed formats in order to check for.
  8936. // Check for ASTC support first as it is most powerful and to be very cross platform.
  8937. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  8938. // Likely no hardware which supports both PVR & DXT, so order matters little.
  8939. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  8940. if (this._caps.astc)
  8941. this.texturesSupported.push('-astc.ktx');
  8942. if (this._caps.s3tc)
  8943. this.texturesSupported.push('-dxt.ktx');
  8944. if (this._caps.pvrtc)
  8945. this.texturesSupported.push('-pvrtc.ktx');
  8946. if (this._caps.etc2)
  8947. this.texturesSupported.push('-etc2.ktx');
  8948. if (this._caps.etc1)
  8949. this.texturesSupported.push('-etc1.ktx');
  8950. if (this._gl.getShaderPrecisionFormat) {
  8951. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  8952. if (highp) {
  8953. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  8954. }
  8955. }
  8956. // Depth buffer
  8957. this.setDepthBuffer(true);
  8958. this.setDepthFunctionToLessOrEqual();
  8959. this.setDepthWrite(true);
  8960. // Texture maps
  8961. for (var slot = 0; slot < this._caps.maxCombinedTexturesImageUnits; slot++) {
  8962. this._nextFreeTextureSlots.push(slot);
  8963. }
  8964. };
  8965. Object.defineProperty(Engine.prototype, "webGLVersion", {
  8966. get: function () {
  8967. return this._webGLVersion;
  8968. },
  8969. enumerable: true,
  8970. configurable: true
  8971. });
  8972. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  8973. /**
  8974. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  8975. */
  8976. get: function () {
  8977. return this._isStencilEnable;
  8978. },
  8979. enumerable: true,
  8980. configurable: true
  8981. });
  8982. Engine.prototype._prepareWorkingCanvas = function () {
  8983. if (this._workingCanvas) {
  8984. return;
  8985. }
  8986. this._workingCanvas = document.createElement("canvas");
  8987. var context = this._workingCanvas.getContext("2d");
  8988. if (context) {
  8989. this._workingContext = context;
  8990. }
  8991. };
  8992. Engine.prototype.resetTextureCache = function () {
  8993. for (var key in this._boundTexturesCache) {
  8994. var boundTexture = this._boundTexturesCache[key];
  8995. if (boundTexture) {
  8996. this._removeDesignatedSlot(boundTexture);
  8997. }
  8998. this._boundTexturesCache[key] = null;
  8999. }
  9000. this._nextFreeTextureSlots = [];
  9001. for (var slot = 0; slot < this._caps.maxCombinedTexturesImageUnits; slot++) {
  9002. this._nextFreeTextureSlots.push(slot);
  9003. }
  9004. this._activeChannel = -1;
  9005. };
  9006. Engine.prototype.isDeterministicLockStep = function () {
  9007. return this._deterministicLockstep;
  9008. };
  9009. Engine.prototype.getLockstepMaxSteps = function () {
  9010. return this._lockstepMaxSteps;
  9011. };
  9012. Engine.prototype.getGlInfo = function () {
  9013. return {
  9014. vendor: this._glVendor,
  9015. renderer: this._glRenderer,
  9016. version: this._glVersion
  9017. };
  9018. };
  9019. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  9020. if (useScreen === void 0) { useScreen = false; }
  9021. var viewport = camera.viewport;
  9022. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  9023. };
  9024. Engine.prototype.getRenderWidth = function (useScreen) {
  9025. if (useScreen === void 0) { useScreen = false; }
  9026. if (!useScreen && this._currentRenderTarget) {
  9027. return this._currentRenderTarget.width;
  9028. }
  9029. return this._gl.drawingBufferWidth;
  9030. };
  9031. Engine.prototype.getRenderHeight = function (useScreen) {
  9032. if (useScreen === void 0) { useScreen = false; }
  9033. if (!useScreen && this._currentRenderTarget) {
  9034. return this._currentRenderTarget.height;
  9035. }
  9036. return this._gl.drawingBufferHeight;
  9037. };
  9038. Engine.prototype.getRenderingCanvas = function () {
  9039. return this._renderingCanvas;
  9040. };
  9041. Engine.prototype.getRenderingCanvasClientRect = function () {
  9042. if (!this._renderingCanvas) {
  9043. return null;
  9044. }
  9045. return this._renderingCanvas.getBoundingClientRect();
  9046. };
  9047. Engine.prototype.setHardwareScalingLevel = function (level) {
  9048. this._hardwareScalingLevel = level;
  9049. this.resize();
  9050. };
  9051. Engine.prototype.getHardwareScalingLevel = function () {
  9052. return this._hardwareScalingLevel;
  9053. };
  9054. Engine.prototype.getLoadedTexturesCache = function () {
  9055. return this._internalTexturesCache;
  9056. };
  9057. Engine.prototype.getCaps = function () {
  9058. return this._caps;
  9059. };
  9060. Object.defineProperty(Engine.prototype, "drawCalls", {
  9061. /** The number of draw calls submitted last frame */
  9062. get: function () {
  9063. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  9064. return 0;
  9065. },
  9066. enumerable: true,
  9067. configurable: true
  9068. });
  9069. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  9070. get: function () {
  9071. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  9072. return null;
  9073. },
  9074. enumerable: true,
  9075. configurable: true
  9076. });
  9077. Engine.prototype.getDepthFunction = function () {
  9078. return this._depthCullingState.depthFunc;
  9079. };
  9080. Engine.prototype.setDepthFunction = function (depthFunc) {
  9081. this._depthCullingState.depthFunc = depthFunc;
  9082. };
  9083. Engine.prototype.setDepthFunctionToGreater = function () {
  9084. this._depthCullingState.depthFunc = this._gl.GREATER;
  9085. };
  9086. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  9087. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  9088. };
  9089. Engine.prototype.setDepthFunctionToLess = function () {
  9090. this._depthCullingState.depthFunc = this._gl.LESS;
  9091. };
  9092. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  9093. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  9094. };
  9095. Engine.prototype.getStencilBuffer = function () {
  9096. return this._stencilState.stencilTest;
  9097. };
  9098. Engine.prototype.setStencilBuffer = function (enable) {
  9099. this._stencilState.stencilTest = enable;
  9100. };
  9101. Engine.prototype.getStencilMask = function () {
  9102. return this._stencilState.stencilMask;
  9103. };
  9104. Engine.prototype.setStencilMask = function (mask) {
  9105. this._stencilState.stencilMask = mask;
  9106. };
  9107. Engine.prototype.getStencilFunction = function () {
  9108. return this._stencilState.stencilFunc;
  9109. };
  9110. Engine.prototype.getStencilFunctionReference = function () {
  9111. return this._stencilState.stencilFuncRef;
  9112. };
  9113. Engine.prototype.getStencilFunctionMask = function () {
  9114. return this._stencilState.stencilFuncMask;
  9115. };
  9116. Engine.prototype.setStencilFunction = function (stencilFunc) {
  9117. this._stencilState.stencilFunc = stencilFunc;
  9118. };
  9119. Engine.prototype.setStencilFunctionReference = function (reference) {
  9120. this._stencilState.stencilFuncRef = reference;
  9121. };
  9122. Engine.prototype.setStencilFunctionMask = function (mask) {
  9123. this._stencilState.stencilFuncMask = mask;
  9124. };
  9125. Engine.prototype.getStencilOperationFail = function () {
  9126. return this._stencilState.stencilOpStencilFail;
  9127. };
  9128. Engine.prototype.getStencilOperationDepthFail = function () {
  9129. return this._stencilState.stencilOpDepthFail;
  9130. };
  9131. Engine.prototype.getStencilOperationPass = function () {
  9132. return this._stencilState.stencilOpStencilDepthPass;
  9133. };
  9134. Engine.prototype.setStencilOperationFail = function (operation) {
  9135. this._stencilState.stencilOpStencilFail = operation;
  9136. };
  9137. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  9138. this._stencilState.stencilOpDepthFail = operation;
  9139. };
  9140. Engine.prototype.setStencilOperationPass = function (operation) {
  9141. this._stencilState.stencilOpStencilDepthPass = operation;
  9142. };
  9143. Engine.prototype.setDitheringState = function (value) {
  9144. if (value) {
  9145. this._gl.enable(this._gl.DITHER);
  9146. }
  9147. else {
  9148. this._gl.disable(this._gl.DITHER);
  9149. }
  9150. };
  9151. Engine.prototype.setRasterizerState = function (value) {
  9152. if (value) {
  9153. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  9154. }
  9155. else {
  9156. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  9157. }
  9158. };
  9159. /**
  9160. * stop executing a render loop function and remove it from the execution array
  9161. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  9162. */
  9163. Engine.prototype.stopRenderLoop = function (renderFunction) {
  9164. if (!renderFunction) {
  9165. this._activeRenderLoops = [];
  9166. return;
  9167. }
  9168. var index = this._activeRenderLoops.indexOf(renderFunction);
  9169. if (index >= 0) {
  9170. this._activeRenderLoops.splice(index, 1);
  9171. }
  9172. };
  9173. Engine.prototype._renderLoop = function () {
  9174. if (!this._contextWasLost) {
  9175. var shouldRender = true;
  9176. if (!this.renderEvenInBackground && this._windowIsBackground) {
  9177. shouldRender = false;
  9178. }
  9179. if (shouldRender) {
  9180. // Start new frame
  9181. this.beginFrame();
  9182. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  9183. var renderFunction = this._activeRenderLoops[index];
  9184. renderFunction();
  9185. }
  9186. // Present
  9187. this.endFrame();
  9188. }
  9189. }
  9190. if (this._activeRenderLoops.length > 0) {
  9191. // Register new frame
  9192. var requester = null;
  9193. if (this._vrDisplay && this._vrDisplay.isPresenting)
  9194. requester = this._vrDisplay;
  9195. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  9196. }
  9197. else {
  9198. this._renderingQueueLaunched = false;
  9199. }
  9200. };
  9201. /**
  9202. * Register and execute a render loop. The engine can have more than one render function.
  9203. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  9204. * @example
  9205. * engine.runRenderLoop(function () {
  9206. * scene.render()
  9207. * })
  9208. */
  9209. Engine.prototype.runRenderLoop = function (renderFunction) {
  9210. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  9211. return;
  9212. }
  9213. this._activeRenderLoops.push(renderFunction);
  9214. if (!this._renderingQueueLaunched) {
  9215. this._renderingQueueLaunched = true;
  9216. this._bindedRenderFunction = this._renderLoop.bind(this);
  9217. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  9218. }
  9219. };
  9220. /**
  9221. * Toggle full screen mode.
  9222. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  9223. * @param {any} options - an options object to be sent to the requestFullscreen function
  9224. */
  9225. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  9226. if (this.isFullscreen) {
  9227. BABYLON.Tools.ExitFullscreen();
  9228. }
  9229. else {
  9230. this._pointerLockRequested = requestPointerLock;
  9231. if (this._renderingCanvas) {
  9232. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  9233. }
  9234. }
  9235. };
  9236. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  9237. if (stencil === void 0) { stencil = false; }
  9238. this.applyStates();
  9239. var mode = 0;
  9240. if (backBuffer && color) {
  9241. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  9242. mode |= this._gl.COLOR_BUFFER_BIT;
  9243. }
  9244. if (depth) {
  9245. this._gl.clearDepth(1.0);
  9246. mode |= this._gl.DEPTH_BUFFER_BIT;
  9247. }
  9248. if (stencil) {
  9249. this._gl.clearStencil(0);
  9250. mode |= this._gl.STENCIL_BUFFER_BIT;
  9251. }
  9252. this._gl.clear(mode);
  9253. };
  9254. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  9255. var gl = this._gl;
  9256. // Save state
  9257. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  9258. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  9259. // Change state
  9260. gl.enable(gl.SCISSOR_TEST);
  9261. gl.scissor(x, y, width, height);
  9262. // Clear
  9263. this.clear(clearColor, true, true, true);
  9264. // Restore state
  9265. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  9266. if (curScissor === true) {
  9267. gl.enable(gl.SCISSOR_TEST);
  9268. }
  9269. else {
  9270. gl.disable(gl.SCISSOR_TEST);
  9271. }
  9272. };
  9273. /**
  9274. * Set the WebGL's viewport
  9275. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  9276. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  9277. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  9278. */
  9279. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  9280. var width = requiredWidth || this.getRenderWidth();
  9281. var height = requiredHeight || this.getRenderHeight();
  9282. var x = viewport.x || 0;
  9283. var y = viewport.y || 0;
  9284. this._cachedViewport = viewport;
  9285. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  9286. };
  9287. /**
  9288. * Directly set the WebGL Viewport
  9289. * The x, y, width & height are directly passed to the WebGL call
  9290. * @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.
  9291. */
  9292. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  9293. var currentViewport = this._cachedViewport;
  9294. this._cachedViewport = null;
  9295. this._gl.viewport(x, y, width, height);
  9296. return currentViewport;
  9297. };
  9298. Engine.prototype.beginFrame = function () {
  9299. this.onBeginFrameObservable.notifyObservers(this);
  9300. this._measureFps();
  9301. };
  9302. Engine.prototype.endFrame = function () {
  9303. //force a flush in case we are using a bad OS.
  9304. if (this._badOS) {
  9305. this.flushFramebuffer();
  9306. }
  9307. //submit frame to the vr device, if enabled
  9308. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  9309. // TODO: We should only submit the frame if we read frameData successfully.
  9310. this._vrDisplay.submitFrame();
  9311. }
  9312. this.onEndFrameObservable.notifyObservers(this);
  9313. };
  9314. /**
  9315. * resize the view according to the canvas' size.
  9316. * @example
  9317. * window.addEventListener("resize", function () {
  9318. * engine.resize();
  9319. * });
  9320. */
  9321. Engine.prototype.resize = function () {
  9322. // We're not resizing the size of the canvas while in VR mode & presenting
  9323. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  9324. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  9325. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  9326. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  9327. }
  9328. };
  9329. /**
  9330. * force a specific size of the canvas
  9331. * @param {number} width - the new canvas' width
  9332. * @param {number} height - the new canvas' height
  9333. */
  9334. Engine.prototype.setSize = function (width, height) {
  9335. if (!this._renderingCanvas) {
  9336. return;
  9337. }
  9338. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  9339. return;
  9340. }
  9341. this._renderingCanvas.width = width;
  9342. this._renderingCanvas.height = height;
  9343. for (var index = 0; index < this.scenes.length; index++) {
  9344. var scene = this.scenes[index];
  9345. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  9346. var cam = scene.cameras[camIndex];
  9347. cam._currentRenderId = 0;
  9348. }
  9349. }
  9350. if (this.onResizeObservable.hasObservers) {
  9351. this.onResizeObservable.notifyObservers(this);
  9352. }
  9353. };
  9354. // WebVR functions
  9355. Engine.prototype.isVRDevicePresent = function () {
  9356. return !!this._vrDisplay;
  9357. };
  9358. Engine.prototype.getVRDevice = function () {
  9359. return this._vrDisplay;
  9360. };
  9361. Engine.prototype.initWebVR = function () {
  9362. var _this = this;
  9363. var notifyObservers = function () {
  9364. var eventArgs = {
  9365. vrDisplay: _this._vrDisplay,
  9366. vrSupported: _this._vrSupported
  9367. };
  9368. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  9369. };
  9370. if (!this._onVrDisplayConnect) {
  9371. this._onVrDisplayConnect = function (event) {
  9372. _this._vrDisplay = event.display;
  9373. notifyObservers();
  9374. };
  9375. this._onVrDisplayDisconnect = function () {
  9376. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  9377. _this._vrDisplay = undefined;
  9378. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  9379. notifyObservers();
  9380. };
  9381. this._onVrDisplayPresentChange = function () {
  9382. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  9383. };
  9384. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  9385. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  9386. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  9387. }
  9388. this._getVRDisplays(notifyObservers);
  9389. return this.onVRDisplayChangedObservable;
  9390. };
  9391. Engine.prototype.enableVR = function () {
  9392. var _this = this;
  9393. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  9394. var onResolved = function () {
  9395. _this.onVRRequestPresentComplete.notifyObservers(true);
  9396. _this._onVRFullScreenTriggered();
  9397. };
  9398. var onRejected = function () {
  9399. _this.onVRRequestPresentComplete.notifyObservers(false);
  9400. };
  9401. this.onVRRequestPresentStart.notifyObservers(this);
  9402. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  9403. }
  9404. };
  9405. Engine.prototype.disableVR = function () {
  9406. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  9407. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  9408. }
  9409. };
  9410. Engine.prototype._getVRDisplays = function (callback) {
  9411. var _this = this;
  9412. var getWebVRDevices = function (devices) {
  9413. _this._vrSupported = true;
  9414. // note that devices may actually be an empty array. This is fine;
  9415. // we expect this._vrDisplay to be undefined in this case.
  9416. return _this._vrDisplay = devices[0];
  9417. };
  9418. if (navigator.getVRDisplays) {
  9419. navigator.getVRDisplays().then(getWebVRDevices).then(callback).catch(function (error) {
  9420. // TODO: System CANNOT support WebVR, despite API presence.
  9421. _this._vrSupported = false;
  9422. callback();
  9423. });
  9424. }
  9425. else {
  9426. // TODO: Browser does not support WebVR
  9427. this._vrDisplay = undefined;
  9428. this._vrSupported = false;
  9429. callback();
  9430. }
  9431. };
  9432. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  9433. if (this._currentRenderTarget) {
  9434. this.unBindFramebuffer(this._currentRenderTarget);
  9435. }
  9436. this._currentRenderTarget = texture;
  9437. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  9438. var gl = this._gl;
  9439. if (texture.isCube) {
  9440. if (faceIndex === undefined) {
  9441. faceIndex = 0;
  9442. }
  9443. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  9444. }
  9445. if (this._cachedViewport && !forceFullscreenViewport) {
  9446. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  9447. }
  9448. else {
  9449. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  9450. }
  9451. this.wipeCaches();
  9452. };
  9453. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  9454. if (this._currentFramebuffer !== framebuffer) {
  9455. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  9456. this._currentFramebuffer = framebuffer;
  9457. }
  9458. };
  9459. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  9460. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  9461. this._currentRenderTarget = null;
  9462. // If MSAA, we need to bitblt back to main texture
  9463. var gl = this._gl;
  9464. if (texture._MSAAFramebuffer) {
  9465. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  9466. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  9467. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  9468. }
  9469. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  9470. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  9471. gl.generateMipmap(gl.TEXTURE_2D);
  9472. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  9473. }
  9474. if (onBeforeUnbind) {
  9475. if (texture._MSAAFramebuffer) {
  9476. // Bind the correct framebuffer
  9477. this.bindUnboundFramebuffer(texture._framebuffer);
  9478. }
  9479. onBeforeUnbind();
  9480. }
  9481. this.bindUnboundFramebuffer(null);
  9482. };
  9483. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  9484. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  9485. this._currentRenderTarget = null;
  9486. // If MSAA, we need to bitblt back to main texture
  9487. var gl = this._gl;
  9488. if (textures[0]._MSAAFramebuffer) {
  9489. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  9490. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  9491. var attachments = textures[0]._attachments;
  9492. if (!attachments) {
  9493. attachments = new Array(textures.length);
  9494. textures[0]._attachments = attachments;
  9495. }
  9496. for (var i = 0; i < textures.length; i++) {
  9497. var texture = textures[i];
  9498. for (var j = 0; j < attachments.length; j++) {
  9499. attachments[j] = gl.NONE;
  9500. }
  9501. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  9502. gl.readBuffer(attachments[i]);
  9503. gl.drawBuffers(attachments);
  9504. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  9505. }
  9506. for (var i = 0; i < attachments.length; i++) {
  9507. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  9508. }
  9509. gl.drawBuffers(attachments);
  9510. }
  9511. for (var i = 0; i < textures.length; i++) {
  9512. var texture = textures[i];
  9513. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  9514. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  9515. gl.generateMipmap(gl.TEXTURE_2D);
  9516. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  9517. }
  9518. }
  9519. if (onBeforeUnbind) {
  9520. if (textures[0]._MSAAFramebuffer) {
  9521. // Bind the correct framebuffer
  9522. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  9523. }
  9524. onBeforeUnbind();
  9525. }
  9526. this.bindUnboundFramebuffer(null);
  9527. };
  9528. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  9529. if (texture.generateMipMaps) {
  9530. var gl = this._gl;
  9531. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  9532. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  9533. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  9534. }
  9535. };
  9536. Engine.prototype.flushFramebuffer = function () {
  9537. this._gl.flush();
  9538. };
  9539. Engine.prototype.restoreDefaultFramebuffer = function () {
  9540. if (this._currentRenderTarget) {
  9541. this.unBindFramebuffer(this._currentRenderTarget);
  9542. }
  9543. else {
  9544. this.bindUnboundFramebuffer(null);
  9545. }
  9546. if (this._cachedViewport) {
  9547. this.setViewport(this._cachedViewport);
  9548. }
  9549. this.wipeCaches();
  9550. };
  9551. // UBOs
  9552. Engine.prototype.createUniformBuffer = function (elements) {
  9553. var ubo = this._gl.createBuffer();
  9554. if (!ubo) {
  9555. throw new Error("Unable to create uniform buffer");
  9556. }
  9557. this.bindUniformBuffer(ubo);
  9558. if (elements instanceof Float32Array) {
  9559. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  9560. }
  9561. else {
  9562. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  9563. }
  9564. this.bindUniformBuffer(null);
  9565. ubo.references = 1;
  9566. return ubo;
  9567. };
  9568. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  9569. var ubo = this._gl.createBuffer();
  9570. if (!ubo) {
  9571. throw new Error("Unable to create dynamic uniform buffer");
  9572. }
  9573. this.bindUniformBuffer(ubo);
  9574. if (elements instanceof Float32Array) {
  9575. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  9576. }
  9577. else {
  9578. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  9579. }
  9580. this.bindUniformBuffer(null);
  9581. ubo.references = 1;
  9582. return ubo;
  9583. };
  9584. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  9585. this.bindUniformBuffer(uniformBuffer);
  9586. if (offset === undefined) {
  9587. offset = 0;
  9588. }
  9589. if (count === undefined) {
  9590. if (elements instanceof Float32Array) {
  9591. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  9592. }
  9593. else {
  9594. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  9595. }
  9596. }
  9597. else {
  9598. if (elements instanceof Float32Array) {
  9599. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  9600. }
  9601. else {
  9602. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  9603. }
  9604. }
  9605. this.bindUniformBuffer(null);
  9606. };
  9607. // VBOs
  9608. Engine.prototype._resetVertexBufferBinding = function () {
  9609. this.bindArrayBuffer(null);
  9610. this._cachedVertexBuffers = null;
  9611. };
  9612. Engine.prototype.createVertexBuffer = function (vertices) {
  9613. var vbo = this._gl.createBuffer();
  9614. if (!vbo) {
  9615. throw new Error("Unable to create vertex buffer");
  9616. }
  9617. this.bindArrayBuffer(vbo);
  9618. if (vertices instanceof Float32Array) {
  9619. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  9620. }
  9621. else {
  9622. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  9623. }
  9624. this._resetVertexBufferBinding();
  9625. vbo.references = 1;
  9626. return vbo;
  9627. };
  9628. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  9629. var vbo = this._gl.createBuffer();
  9630. if (!vbo) {
  9631. throw new Error("Unable to create dynamic vertex buffer");
  9632. }
  9633. this.bindArrayBuffer(vbo);
  9634. if (vertices instanceof Float32Array) {
  9635. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  9636. }
  9637. else {
  9638. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  9639. }
  9640. this._resetVertexBufferBinding();
  9641. vbo.references = 1;
  9642. return vbo;
  9643. };
  9644. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  9645. if (offset === void 0) { offset = 0; }
  9646. // Force cache update
  9647. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  9648. this.bindIndexBuffer(indexBuffer);
  9649. var arrayBuffer;
  9650. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  9651. arrayBuffer = indices;
  9652. }
  9653. else {
  9654. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  9655. }
  9656. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  9657. this._resetIndexBufferBinding();
  9658. };
  9659. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  9660. this.bindArrayBuffer(vertexBuffer);
  9661. if (offset === undefined) {
  9662. offset = 0;
  9663. }
  9664. if (count === undefined) {
  9665. if (vertices instanceof Float32Array) {
  9666. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  9667. }
  9668. else {
  9669. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  9670. }
  9671. }
  9672. else {
  9673. if (vertices instanceof Float32Array) {
  9674. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  9675. }
  9676. else {
  9677. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  9678. }
  9679. }
  9680. this._resetVertexBufferBinding();
  9681. };
  9682. Engine.prototype._resetIndexBufferBinding = function () {
  9683. this.bindIndexBuffer(null);
  9684. this._cachedIndexBuffer = null;
  9685. };
  9686. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  9687. var vbo = this._gl.createBuffer();
  9688. if (!vbo) {
  9689. throw new Error("Unable to create index buffer");
  9690. }
  9691. this.bindIndexBuffer(vbo);
  9692. // Check for 32 bits indices
  9693. var arrayBuffer;
  9694. var need32Bits = false;
  9695. if (indices instanceof Uint16Array) {
  9696. arrayBuffer = indices;
  9697. }
  9698. else {
  9699. //check 32 bit support
  9700. if (this._caps.uintIndices) {
  9701. if (indices instanceof Uint32Array) {
  9702. arrayBuffer = indices;
  9703. need32Bits = true;
  9704. }
  9705. else {
  9706. //number[] or Int32Array, check if 32 bit is necessary
  9707. for (var index = 0; index < indices.length; index++) {
  9708. if (indices[index] > 65535) {
  9709. need32Bits = true;
  9710. break;
  9711. }
  9712. }
  9713. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  9714. }
  9715. }
  9716. else {
  9717. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  9718. arrayBuffer = new Uint16Array(indices);
  9719. }
  9720. }
  9721. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  9722. this._resetIndexBufferBinding();
  9723. vbo.references = 1;
  9724. vbo.is32Bits = need32Bits;
  9725. return vbo;
  9726. };
  9727. Engine.prototype.bindArrayBuffer = function (buffer) {
  9728. if (!this._vaoRecordInProgress) {
  9729. this._unbindVertexArrayObject();
  9730. }
  9731. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  9732. };
  9733. Engine.prototype.bindUniformBuffer = function (buffer) {
  9734. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  9735. };
  9736. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  9737. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  9738. };
  9739. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  9740. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  9741. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  9742. };
  9743. ;
  9744. Engine.prototype.bindIndexBuffer = function (buffer) {
  9745. if (!this._vaoRecordInProgress) {
  9746. this._unbindVertexArrayObject();
  9747. }
  9748. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  9749. };
  9750. Engine.prototype.bindBuffer = function (buffer, target) {
  9751. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  9752. this._gl.bindBuffer(target, buffer);
  9753. this._currentBoundBuffer[target] = buffer;
  9754. }
  9755. };
  9756. Engine.prototype.updateArrayBuffer = function (data) {
  9757. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  9758. };
  9759. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  9760. var pointer = this._currentBufferPointers[indx];
  9761. var changed = false;
  9762. if (!pointer.active) {
  9763. changed = true;
  9764. pointer.active = true;
  9765. pointer.index = indx;
  9766. pointer.size = size;
  9767. pointer.type = type;
  9768. pointer.normalized = normalized;
  9769. pointer.stride = stride;
  9770. pointer.offset = offset;
  9771. pointer.buffer = buffer;
  9772. }
  9773. else {
  9774. if (pointer.buffer !== buffer) {
  9775. pointer.buffer = buffer;
  9776. changed = true;
  9777. }
  9778. if (pointer.size !== size) {
  9779. pointer.size = size;
  9780. changed = true;
  9781. }
  9782. if (pointer.type !== type) {
  9783. pointer.type = type;
  9784. changed = true;
  9785. }
  9786. if (pointer.normalized !== normalized) {
  9787. pointer.normalized = normalized;
  9788. changed = true;
  9789. }
  9790. if (pointer.stride !== stride) {
  9791. pointer.stride = stride;
  9792. changed = true;
  9793. }
  9794. if (pointer.offset !== offset) {
  9795. pointer.offset = offset;
  9796. changed = true;
  9797. }
  9798. }
  9799. if (changed || this._vaoRecordInProgress) {
  9800. this.bindArrayBuffer(buffer);
  9801. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  9802. }
  9803. };
  9804. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  9805. if (indexBuffer == null) {
  9806. return;
  9807. }
  9808. if (this._cachedIndexBuffer !== indexBuffer) {
  9809. this._cachedIndexBuffer = indexBuffer;
  9810. this.bindIndexBuffer(indexBuffer);
  9811. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  9812. }
  9813. };
  9814. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  9815. var attributes = effect.getAttributesNames();
  9816. if (!this._vaoRecordInProgress) {
  9817. this._unbindVertexArrayObject();
  9818. }
  9819. this.unbindAllAttributes();
  9820. for (var index = 0; index < attributes.length; index++) {
  9821. var order = effect.getAttributeLocation(index);
  9822. if (order >= 0) {
  9823. var vertexBuffer = vertexBuffers[attributes[index]];
  9824. if (!vertexBuffer) {
  9825. continue;
  9826. }
  9827. this._gl.enableVertexAttribArray(order);
  9828. if (!this._vaoRecordInProgress) {
  9829. this._vertexAttribArraysEnabled[order] = true;
  9830. }
  9831. var buffer = vertexBuffer.getBuffer();
  9832. if (buffer) {
  9833. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  9834. if (vertexBuffer.getIsInstanced()) {
  9835. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  9836. if (!this._vaoRecordInProgress) {
  9837. this._currentInstanceLocations.push(order);
  9838. this._currentInstanceBuffers.push(buffer);
  9839. }
  9840. }
  9841. }
  9842. }
  9843. }
  9844. };
  9845. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  9846. var vao = this._gl.createVertexArray();
  9847. this._vaoRecordInProgress = true;
  9848. this._gl.bindVertexArray(vao);
  9849. this._mustWipeVertexAttributes = true;
  9850. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  9851. this.bindIndexBuffer(indexBuffer);
  9852. this._vaoRecordInProgress = false;
  9853. this._gl.bindVertexArray(null);
  9854. return vao;
  9855. };
  9856. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  9857. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  9858. this._cachedVertexArrayObject = vertexArrayObject;
  9859. this._gl.bindVertexArray(vertexArrayObject);
  9860. this._cachedVertexBuffers = null;
  9861. this._cachedIndexBuffer = null;
  9862. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  9863. this._mustWipeVertexAttributes = true;
  9864. }
  9865. };
  9866. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  9867. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  9868. this._cachedVertexBuffers = vertexBuffer;
  9869. this._cachedEffectForVertexBuffers = effect;
  9870. var attributesCount = effect.getAttributesCount();
  9871. this._unbindVertexArrayObject();
  9872. this.unbindAllAttributes();
  9873. var offset = 0;
  9874. for (var index = 0; index < attributesCount; index++) {
  9875. if (index < vertexDeclaration.length) {
  9876. var order = effect.getAttributeLocation(index);
  9877. if (order >= 0) {
  9878. this._gl.enableVertexAttribArray(order);
  9879. this._vertexAttribArraysEnabled[order] = true;
  9880. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  9881. }
  9882. offset += vertexDeclaration[index] * 4;
  9883. }
  9884. }
  9885. }
  9886. this._bindIndexBufferWithCache(indexBuffer);
  9887. };
  9888. Engine.prototype._unbindVertexArrayObject = function () {
  9889. if (!this._cachedVertexArrayObject) {
  9890. return;
  9891. }
  9892. this._cachedVertexArrayObject = null;
  9893. this._gl.bindVertexArray(null);
  9894. };
  9895. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  9896. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  9897. this._cachedVertexBuffers = vertexBuffers;
  9898. this._cachedEffectForVertexBuffers = effect;
  9899. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  9900. }
  9901. this._bindIndexBufferWithCache(indexBuffer);
  9902. };
  9903. Engine.prototype.unbindInstanceAttributes = function () {
  9904. var boundBuffer;
  9905. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  9906. var instancesBuffer = this._currentInstanceBuffers[i];
  9907. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  9908. boundBuffer = instancesBuffer;
  9909. this.bindArrayBuffer(instancesBuffer);
  9910. }
  9911. var offsetLocation = this._currentInstanceLocations[i];
  9912. this._gl.vertexAttribDivisor(offsetLocation, 0);
  9913. }
  9914. this._currentInstanceBuffers.length = 0;
  9915. this._currentInstanceLocations.length = 0;
  9916. };
  9917. Engine.prototype.releaseVertexArrayObject = function (vao) {
  9918. this._gl.deleteVertexArray(vao);
  9919. };
  9920. Engine.prototype._releaseBuffer = function (buffer) {
  9921. buffer.references--;
  9922. if (buffer.references === 0) {
  9923. this._gl.deleteBuffer(buffer);
  9924. return true;
  9925. }
  9926. return false;
  9927. };
  9928. Engine.prototype.createInstancesBuffer = function (capacity) {
  9929. var buffer = this._gl.createBuffer();
  9930. if (!buffer) {
  9931. throw new Error("Unable to create instance buffer");
  9932. }
  9933. buffer.capacity = capacity;
  9934. this.bindArrayBuffer(buffer);
  9935. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  9936. return buffer;
  9937. };
  9938. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  9939. this._gl.deleteBuffer(buffer);
  9940. };
  9941. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  9942. this.bindArrayBuffer(instancesBuffer);
  9943. if (data) {
  9944. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  9945. }
  9946. if (offsetLocations[0].index !== undefined) {
  9947. var stride = 0;
  9948. for (var i = 0; i < offsetLocations.length; i++) {
  9949. var ai = offsetLocations[i];
  9950. stride += ai.attributeSize * 4;
  9951. }
  9952. for (var i = 0; i < offsetLocations.length; i++) {
  9953. var ai = offsetLocations[i];
  9954. if (!this._vertexAttribArraysEnabled[ai.index]) {
  9955. this._gl.enableVertexAttribArray(ai.index);
  9956. this._vertexAttribArraysEnabled[ai.index] = true;
  9957. }
  9958. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  9959. this._gl.vertexAttribDivisor(ai.index, 1);
  9960. this._currentInstanceLocations.push(ai.index);
  9961. this._currentInstanceBuffers.push(instancesBuffer);
  9962. }
  9963. }
  9964. else {
  9965. for (var index = 0; index < 4; index++) {
  9966. var offsetLocation = offsetLocations[index];
  9967. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  9968. this._gl.enableVertexAttribArray(offsetLocation);
  9969. this._vertexAttribArraysEnabled[offsetLocation] = true;
  9970. }
  9971. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  9972. this._gl.vertexAttribDivisor(offsetLocation, 1);
  9973. this._currentInstanceLocations.push(offsetLocation);
  9974. this._currentInstanceBuffers.push(instancesBuffer);
  9975. }
  9976. }
  9977. };
  9978. Engine.prototype.applyStates = function () {
  9979. this._depthCullingState.apply(this._gl);
  9980. this._stencilState.apply(this._gl);
  9981. this._alphaState.apply(this._gl);
  9982. };
  9983. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  9984. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  9985. };
  9986. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  9987. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  9988. };
  9989. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  9990. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  9991. };
  9992. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  9993. // Apply states
  9994. this.applyStates();
  9995. this._drawCalls.addCount(1, false);
  9996. // Render
  9997. var drawMode = this.DrawMode(fillMode);
  9998. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  9999. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  10000. if (instancesCount) {
  10001. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  10002. }
  10003. else {
  10004. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  10005. }
  10006. };
  10007. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  10008. // Apply states
  10009. this.applyStates();
  10010. this._drawCalls.addCount(1, false);
  10011. var drawMode = this.DrawMode(fillMode);
  10012. if (instancesCount) {
  10013. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  10014. }
  10015. else {
  10016. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  10017. }
  10018. };
  10019. Engine.prototype.DrawMode = function (fillMode) {
  10020. switch (fillMode) {
  10021. // Triangle views
  10022. case BABYLON.Material.TriangleFillMode:
  10023. return this._gl.TRIANGLES;
  10024. case BABYLON.Material.PointFillMode:
  10025. return this._gl.POINTS;
  10026. case BABYLON.Material.WireFrameFillMode:
  10027. return this._gl.LINES;
  10028. // Draw modes
  10029. case BABYLON.Material.PointListDrawMode:
  10030. return this._gl.POINTS;
  10031. case BABYLON.Material.LineListDrawMode:
  10032. return this._gl.LINES;
  10033. case BABYLON.Material.LineLoopDrawMode:
  10034. return this._gl.LINE_LOOP;
  10035. case BABYLON.Material.LineStripDrawMode:
  10036. return this._gl.LINE_STRIP;
  10037. case BABYLON.Material.TriangleStripDrawMode:
  10038. return this._gl.TRIANGLE_STRIP;
  10039. case BABYLON.Material.TriangleFanDrawMode:
  10040. return this._gl.TRIANGLE_FAN;
  10041. default:
  10042. return this._gl.TRIANGLES;
  10043. }
  10044. };
  10045. // Shaders
  10046. Engine.prototype._releaseEffect = function (effect) {
  10047. if (this._compiledEffects[effect._key]) {
  10048. delete this._compiledEffects[effect._key];
  10049. this._deleteProgram(effect.getProgram());
  10050. }
  10051. };
  10052. Engine.prototype._deleteProgram = function (program) {
  10053. if (program) {
  10054. program.__SPECTOR_rebuildProgram = null;
  10055. if (program.transformFeedback) {
  10056. this.deleteTransformFeedback(program.transformFeedback);
  10057. program.transformFeedback = null;
  10058. }
  10059. this._gl.deleteProgram(program);
  10060. }
  10061. };
  10062. /**
  10063. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  10064. * @param samplers An array of string used to represent textures
  10065. */
  10066. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  10067. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  10068. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  10069. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  10070. if (this._compiledEffects[name]) {
  10071. var compiledEffect = this._compiledEffects[name];
  10072. if (onCompiled && compiledEffect.isReady()) {
  10073. onCompiled(compiledEffect);
  10074. }
  10075. return compiledEffect;
  10076. }
  10077. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  10078. effect._key = name;
  10079. this._compiledEffects[name] = effect;
  10080. return effect;
  10081. };
  10082. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  10083. if (uniformsNames === void 0) { uniformsNames = []; }
  10084. if (samplers === void 0) { samplers = []; }
  10085. if (defines === void 0) { defines = ""; }
  10086. return this.createEffect({
  10087. vertex: "particles",
  10088. fragmentElement: fragmentName
  10089. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  10090. };
  10091. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  10092. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  10093. context = context || this._gl;
  10094. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  10095. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  10096. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  10097. };
  10098. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  10099. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  10100. context = context || this._gl;
  10101. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  10102. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  10103. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  10104. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  10105. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  10106. this.onAfterShaderCompilationObservable.notifyObservers(this);
  10107. return program;
  10108. };
  10109. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  10110. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  10111. var shaderProgram = context.createProgram();
  10112. if (!shaderProgram) {
  10113. throw new Error("Unable to create program");
  10114. }
  10115. context.attachShader(shaderProgram, vertexShader);
  10116. context.attachShader(shaderProgram, fragmentShader);
  10117. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  10118. var transformFeedback = this.createTransformFeedback();
  10119. this.bindTransformFeedback(transformFeedback);
  10120. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  10121. shaderProgram.transformFeedback = transformFeedback;
  10122. }
  10123. context.linkProgram(shaderProgram);
  10124. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  10125. this.bindTransformFeedback(null);
  10126. }
  10127. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  10128. if (!linked) {
  10129. context.validateProgram(shaderProgram);
  10130. var error = context.getProgramInfoLog(shaderProgram);
  10131. if (error) {
  10132. throw new Error(error);
  10133. }
  10134. }
  10135. context.deleteShader(vertexShader);
  10136. context.deleteShader(fragmentShader);
  10137. return shaderProgram;
  10138. };
  10139. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  10140. var results = new Array();
  10141. for (var index = 0; index < uniformsNames.length; index++) {
  10142. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  10143. }
  10144. return results;
  10145. };
  10146. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  10147. var results = [];
  10148. for (var index = 0; index < attributesNames.length; index++) {
  10149. try {
  10150. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  10151. }
  10152. catch (e) {
  10153. results.push(-1);
  10154. }
  10155. }
  10156. return results;
  10157. };
  10158. Engine.prototype.enableEffect = function (effect) {
  10159. if (!effect) {
  10160. return;
  10161. }
  10162. // Use program
  10163. this.bindSamplers(effect);
  10164. this._currentEffect = effect;
  10165. if (effect.onBind) {
  10166. effect.onBind(effect);
  10167. }
  10168. effect.onBindObservable.notifyObservers(effect);
  10169. };
  10170. Engine.prototype.setIntArray = function (uniform, array) {
  10171. if (!uniform)
  10172. return;
  10173. this._gl.uniform1iv(uniform, array);
  10174. };
  10175. Engine.prototype.setIntArray2 = function (uniform, array) {
  10176. if (!uniform || array.length % 2 !== 0)
  10177. return;
  10178. this._gl.uniform2iv(uniform, array);
  10179. };
  10180. Engine.prototype.setIntArray3 = function (uniform, array) {
  10181. if (!uniform || array.length % 3 !== 0)
  10182. return;
  10183. this._gl.uniform3iv(uniform, array);
  10184. };
  10185. Engine.prototype.setIntArray4 = function (uniform, array) {
  10186. if (!uniform || array.length % 4 !== 0)
  10187. return;
  10188. this._gl.uniform4iv(uniform, array);
  10189. };
  10190. Engine.prototype.setFloatArray = function (uniform, array) {
  10191. if (!uniform)
  10192. return;
  10193. this._gl.uniform1fv(uniform, array);
  10194. };
  10195. Engine.prototype.setFloatArray2 = function (uniform, array) {
  10196. if (!uniform || array.length % 2 !== 0)
  10197. return;
  10198. this._gl.uniform2fv(uniform, array);
  10199. };
  10200. Engine.prototype.setFloatArray3 = function (uniform, array) {
  10201. if (!uniform || array.length % 3 !== 0)
  10202. return;
  10203. this._gl.uniform3fv(uniform, array);
  10204. };
  10205. Engine.prototype.setFloatArray4 = function (uniform, array) {
  10206. if (!uniform || array.length % 4 !== 0)
  10207. return;
  10208. this._gl.uniform4fv(uniform, array);
  10209. };
  10210. Engine.prototype.setArray = function (uniform, array) {
  10211. if (!uniform)
  10212. return;
  10213. this._gl.uniform1fv(uniform, array);
  10214. };
  10215. Engine.prototype.setArray2 = function (uniform, array) {
  10216. if (!uniform || array.length % 2 !== 0)
  10217. return;
  10218. this._gl.uniform2fv(uniform, array);
  10219. };
  10220. Engine.prototype.setArray3 = function (uniform, array) {
  10221. if (!uniform || array.length % 3 !== 0)
  10222. return;
  10223. this._gl.uniform3fv(uniform, array);
  10224. };
  10225. Engine.prototype.setArray4 = function (uniform, array) {
  10226. if (!uniform || array.length % 4 !== 0)
  10227. return;
  10228. this._gl.uniform4fv(uniform, array);
  10229. };
  10230. Engine.prototype.setMatrices = function (uniform, matrices) {
  10231. if (!uniform)
  10232. return;
  10233. this._gl.uniformMatrix4fv(uniform, false, matrices);
  10234. };
  10235. Engine.prototype.setMatrix = function (uniform, matrix) {
  10236. if (!uniform)
  10237. return;
  10238. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  10239. };
  10240. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  10241. if (!uniform)
  10242. return;
  10243. this._gl.uniformMatrix3fv(uniform, false, matrix);
  10244. };
  10245. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  10246. if (!uniform)
  10247. return;
  10248. this._gl.uniformMatrix2fv(uniform, false, matrix);
  10249. };
  10250. Engine.prototype.setInt = function (uniform, value) {
  10251. if (!uniform)
  10252. return;
  10253. this._gl.uniform1i(uniform, value);
  10254. };
  10255. Engine.prototype.setFloat = function (uniform, value) {
  10256. if (!uniform)
  10257. return;
  10258. this._gl.uniform1f(uniform, value);
  10259. };
  10260. Engine.prototype.setFloat2 = function (uniform, x, y) {
  10261. if (!uniform)
  10262. return;
  10263. this._gl.uniform2f(uniform, x, y);
  10264. };
  10265. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  10266. if (!uniform)
  10267. return;
  10268. this._gl.uniform3f(uniform, x, y, z);
  10269. };
  10270. Engine.prototype.setBool = function (uniform, bool) {
  10271. if (!uniform)
  10272. return;
  10273. this._gl.uniform1i(uniform, bool);
  10274. };
  10275. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  10276. if (!uniform)
  10277. return;
  10278. this._gl.uniform4f(uniform, x, y, z, w);
  10279. };
  10280. Engine.prototype.setColor3 = function (uniform, color3) {
  10281. if (!uniform)
  10282. return;
  10283. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  10284. };
  10285. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  10286. if (!uniform)
  10287. return;
  10288. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  10289. };
  10290. // States
  10291. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  10292. if (zOffset === void 0) { zOffset = 0; }
  10293. if (reverseSide === void 0) { reverseSide = false; }
  10294. // Culling
  10295. if (this._depthCullingState.cull !== culling || force) {
  10296. this._depthCullingState.cull = culling;
  10297. }
  10298. // Cull face
  10299. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  10300. if (this._depthCullingState.cullFace !== cullFace || force) {
  10301. this._depthCullingState.cullFace = cullFace;
  10302. }
  10303. // Z offset
  10304. this.setZOffset(zOffset);
  10305. // Front face
  10306. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  10307. if (this._depthCullingState.frontFace !== frontFace || force) {
  10308. this._depthCullingState.frontFace = frontFace;
  10309. }
  10310. };
  10311. Engine.prototype.setZOffset = function (value) {
  10312. this._depthCullingState.zOffset = value;
  10313. };
  10314. Engine.prototype.getZOffset = function () {
  10315. return this._depthCullingState.zOffset;
  10316. };
  10317. Engine.prototype.setDepthBuffer = function (enable) {
  10318. this._depthCullingState.depthTest = enable;
  10319. };
  10320. Engine.prototype.getDepthWrite = function () {
  10321. return this._depthCullingState.depthMask;
  10322. };
  10323. Engine.prototype.setDepthWrite = function (enable) {
  10324. this._depthCullingState.depthMask = enable;
  10325. };
  10326. Engine.prototype.setColorWrite = function (enable) {
  10327. this._gl.colorMask(enable, enable, enable, enable);
  10328. this._colorWrite = enable;
  10329. };
  10330. Engine.prototype.getColorWrite = function () {
  10331. return this._colorWrite;
  10332. };
  10333. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  10334. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  10335. };
  10336. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  10337. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  10338. if (this._alphaMode === mode) {
  10339. return;
  10340. }
  10341. switch (mode) {
  10342. case Engine.ALPHA_DISABLE:
  10343. this._alphaState.alphaBlend = false;
  10344. break;
  10345. case Engine.ALPHA_PREMULTIPLIED:
  10346. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  10347. this._alphaState.alphaBlend = true;
  10348. break;
  10349. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  10350. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  10351. this._alphaState.alphaBlend = true;
  10352. break;
  10353. case Engine.ALPHA_COMBINE:
  10354. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  10355. this._alphaState.alphaBlend = true;
  10356. break;
  10357. case Engine.ALPHA_ONEONE:
  10358. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  10359. this._alphaState.alphaBlend = true;
  10360. break;
  10361. case Engine.ALPHA_ADD:
  10362. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  10363. this._alphaState.alphaBlend = true;
  10364. break;
  10365. case Engine.ALPHA_SUBTRACT:
  10366. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  10367. this._alphaState.alphaBlend = true;
  10368. break;
  10369. case Engine.ALPHA_MULTIPLY:
  10370. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  10371. this._alphaState.alphaBlend = true;
  10372. break;
  10373. case Engine.ALPHA_MAXIMIZED:
  10374. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  10375. this._alphaState.alphaBlend = true;
  10376. break;
  10377. case Engine.ALPHA_INTERPOLATE:
  10378. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  10379. this._alphaState.alphaBlend = true;
  10380. break;
  10381. case Engine.ALPHA_SCREENMODE:
  10382. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  10383. this._alphaState.alphaBlend = true;
  10384. break;
  10385. }
  10386. if (!noDepthWriteChange) {
  10387. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  10388. }
  10389. this._alphaMode = mode;
  10390. };
  10391. Engine.prototype.getAlphaMode = function () {
  10392. return this._alphaMode;
  10393. };
  10394. Engine.prototype.setAlphaTesting = function (enable) {
  10395. this._alphaTest = enable;
  10396. };
  10397. Engine.prototype.getAlphaTesting = function () {
  10398. return !!this._alphaTest;
  10399. };
  10400. // Textures
  10401. Engine.prototype.wipeCaches = function (bruteForce) {
  10402. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  10403. return;
  10404. }
  10405. this._currentEffect = null;
  10406. // 6/8/2017: deltakosh: Should not be required anymore.
  10407. // This message is then mostly for the future myself who will scream out loud when seeing that it was actually required :)
  10408. if (bruteForce) {
  10409. this.resetTextureCache();
  10410. this._currentProgram = null;
  10411. this._stencilState.reset();
  10412. this._depthCullingState.reset();
  10413. this.setDepthFunctionToLessOrEqual();
  10414. this._alphaState.reset();
  10415. }
  10416. this._resetVertexBufferBinding();
  10417. this._cachedIndexBuffer = null;
  10418. this._cachedEffectForVertexBuffers = null;
  10419. this._unbindVertexArrayObject();
  10420. this.bindIndexBuffer(null);
  10421. };
  10422. /**
  10423. * Set the compressed texture format to use, based on the formats you have, and the formats
  10424. * supported by the hardware / browser.
  10425. *
  10426. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  10427. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  10428. * to API arguments needed to compressed textures. This puts the burden on the container
  10429. * generator to house the arcane code for determining these for current & future formats.
  10430. *
  10431. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  10432. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  10433. *
  10434. * Note: The result of this call is not taken into account when a texture is base64.
  10435. *
  10436. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  10437. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  10438. *
  10439. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  10440. * @returns The extension selected.
  10441. */
  10442. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  10443. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  10444. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  10445. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  10446. return this._textureFormatInUse = this._texturesSupported[i];
  10447. }
  10448. }
  10449. }
  10450. // actively set format to nothing, to allow this to be called more than once
  10451. // and possibly fail the 2nd time
  10452. this._textureFormatInUse = null;
  10453. return null;
  10454. };
  10455. Engine.prototype._createTexture = function () {
  10456. var texture = this._gl.createTexture();
  10457. if (!texture) {
  10458. throw new Error("Unable to create texture");
  10459. }
  10460. return texture;
  10461. };
  10462. /**
  10463. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  10464. * @param {string} urlArg- This contains one of the following:
  10465. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  10466. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  10467. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  10468. *
  10469. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  10470. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  10471. * @param {Scene} scene- Needed for loading to the correct scene.
  10472. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  10473. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  10474. * @param {callback} onError- Optional callback to be called upon failure.
  10475. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  10476. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  10477. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  10478. *
  10479. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  10480. */
  10481. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  10482. var _this = this;
  10483. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  10484. if (onLoad === void 0) { onLoad = null; }
  10485. if (onError === void 0) { onError = null; }
  10486. if (buffer === void 0) { buffer = null; }
  10487. if (fallBack === void 0) { fallBack = null; }
  10488. if (format === void 0) { format = null; }
  10489. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  10490. var fromData = url.substr(0, 5) === "data:";
  10491. var fromBlob = url.substr(0, 5) === "blob:";
  10492. var isBase64 = fromData && url.indexOf("base64") !== -1;
  10493. var texture = fallBack ? fallBack : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  10494. // establish the file extension, if possible
  10495. var lastDot = url.lastIndexOf('.');
  10496. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  10497. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  10498. var isTGA = (extension === ".tga");
  10499. // determine if a ktx file should be substituted
  10500. var isKTX = false;
  10501. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  10502. url = url.substring(0, lastDot) + this._textureFormatInUse;
  10503. isKTX = true;
  10504. }
  10505. if (scene) {
  10506. scene._addPendingData(texture);
  10507. }
  10508. texture.url = url;
  10509. texture.generateMipMaps = !noMipmap;
  10510. texture.samplingMode = samplingMode;
  10511. texture.invertY = invertY;
  10512. if (!this._doNotHandleContextLost) {
  10513. // Keep a link to the buffer only if we plan to handle context lost
  10514. texture._buffer = buffer;
  10515. }
  10516. var onLoadObserver = null;
  10517. if (onLoad && !fallBack) {
  10518. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  10519. }
  10520. if (!fallBack)
  10521. this._internalTexturesCache.push(texture);
  10522. var onerror = function (message, exception) {
  10523. if (scene) {
  10524. scene._removePendingData(texture);
  10525. }
  10526. if (onLoadObserver) {
  10527. texture.onLoadedObservable.remove(onLoadObserver);
  10528. }
  10529. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  10530. if (isKTX) {
  10531. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  10532. }
  10533. else if (BABYLON.Tools.UseFallbackTexture) {
  10534. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  10535. }
  10536. if (onError) {
  10537. onError(message || "Unknown error", exception);
  10538. }
  10539. };
  10540. var callback = null;
  10541. // processing for non-image formats
  10542. if (isKTX || isTGA || isDDS) {
  10543. if (isKTX) {
  10544. callback = function (data) {
  10545. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 1);
  10546. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  10547. ktx.uploadLevels(_this._gl, !noMipmap);
  10548. return false;
  10549. }, samplingMode);
  10550. };
  10551. }
  10552. else if (isTGA) {
  10553. callback = function (arrayBuffer) {
  10554. var data = new Uint8Array(arrayBuffer);
  10555. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  10556. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  10557. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  10558. return false;
  10559. }, samplingMode);
  10560. };
  10561. }
  10562. else if (isDDS) {
  10563. callback = function (data) {
  10564. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  10565. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  10566. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  10567. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  10568. return false;
  10569. }, samplingMode);
  10570. };
  10571. }
  10572. if (!buffer) {
  10573. this._loadFile(url, function (data) {
  10574. if (callback) {
  10575. callback(data);
  10576. }
  10577. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  10578. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  10579. });
  10580. }
  10581. else {
  10582. if (callback) {
  10583. callback(buffer);
  10584. }
  10585. }
  10586. // image format processing
  10587. }
  10588. else {
  10589. var onload = function (img) {
  10590. if (fromBlob && !_this._doNotHandleContextLost) {
  10591. // We need to store the image if we need to rebuild the texture
  10592. // in case of a webgl context lost
  10593. texture._buffer = img;
  10594. }
  10595. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  10596. var gl = _this._gl;
  10597. var isPot = (img.width === potWidth && img.height === potHeight);
  10598. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  10599. if (isPot) {
  10600. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  10601. return false;
  10602. }
  10603. // Using shaders to rescale because canvas.drawImage is lossy
  10604. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  10605. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  10606. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  10607. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10608. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  10609. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10610. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10611. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  10612. _this._releaseTexture(source);
  10613. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  10614. continuationCallback();
  10615. });
  10616. return true;
  10617. }, samplingMode);
  10618. };
  10619. if (!fromData || isBase64)
  10620. if (buffer instanceof HTMLImageElement) {
  10621. onload(buffer);
  10622. }
  10623. else {
  10624. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  10625. }
  10626. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  10627. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  10628. else
  10629. onload(buffer);
  10630. }
  10631. return texture;
  10632. };
  10633. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  10634. var _this = this;
  10635. var rtt = this.createRenderTargetTexture({
  10636. width: destination.width,
  10637. height: destination.height,
  10638. }, {
  10639. generateMipMaps: false,
  10640. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  10641. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  10642. generateDepthBuffer: false,
  10643. generateStencilBuffer: false
  10644. });
  10645. if (!this._rescalePostProcess) {
  10646. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  10647. }
  10648. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  10649. _this._rescalePostProcess.onApply = function (effect) {
  10650. effect._bindTexture("textureSampler", source);
  10651. };
  10652. var hostingScene = scene;
  10653. if (!hostingScene) {
  10654. hostingScene = _this.scenes[_this.scenes.length - 1];
  10655. }
  10656. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  10657. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  10658. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  10659. _this.unBindFramebuffer(rtt);
  10660. _this._releaseTexture(rtt);
  10661. if (onComplete) {
  10662. onComplete();
  10663. }
  10664. });
  10665. };
  10666. Engine.prototype._getInternalFormat = function (format) {
  10667. var internalFormat = this._gl.RGBA;
  10668. switch (format) {
  10669. case Engine.TEXTUREFORMAT_ALPHA:
  10670. internalFormat = this._gl.ALPHA;
  10671. break;
  10672. case Engine.TEXTUREFORMAT_LUMINANCE:
  10673. internalFormat = this._gl.LUMINANCE;
  10674. break;
  10675. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  10676. internalFormat = this._gl.LUMINANCE_ALPHA;
  10677. break;
  10678. case Engine.TEXTUREFORMAT_RGB:
  10679. internalFormat = this._gl.RGB;
  10680. break;
  10681. case Engine.TEXTUREFORMAT_RGBA:
  10682. internalFormat = this._gl.RGBA;
  10683. break;
  10684. }
  10685. return internalFormat;
  10686. };
  10687. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  10688. if (compression === void 0) { compression = null; }
  10689. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  10690. if (!texture) {
  10691. return;
  10692. }
  10693. var internalFormat = this._getInternalFormat(format);
  10694. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  10695. var textureType = this._getWebGLTextureType(type);
  10696. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  10697. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  10698. if (!this._doNotHandleContextLost) {
  10699. texture._bufferView = data;
  10700. texture.format = format;
  10701. texture.type = type;
  10702. texture.invertY = invertY;
  10703. texture._compression = compression;
  10704. }
  10705. if (texture.width % 4 !== 0) {
  10706. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  10707. }
  10708. if (compression && data) {
  10709. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  10710. }
  10711. else {
  10712. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  10713. }
  10714. if (texture.generateMipMaps) {
  10715. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10716. }
  10717. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10718. // this.resetTextureCache();
  10719. texture.isReady = true;
  10720. };
  10721. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  10722. if (compression === void 0) { compression = null; }
  10723. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  10724. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  10725. texture.baseWidth = width;
  10726. texture.baseHeight = height;
  10727. texture.width = width;
  10728. texture.height = height;
  10729. texture.format = format;
  10730. texture.generateMipMaps = generateMipMaps;
  10731. texture.samplingMode = samplingMode;
  10732. texture.invertY = invertY;
  10733. texture._compression = compression;
  10734. texture.type = type;
  10735. if (!this._doNotHandleContextLost) {
  10736. texture._bufferView = data;
  10737. }
  10738. this.updateRawTexture(texture, data, format, invertY, compression, type);
  10739. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  10740. // Filters
  10741. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  10742. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  10743. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  10744. if (generateMipMaps) {
  10745. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10746. }
  10747. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10748. this._internalTexturesCache.push(texture);
  10749. return texture;
  10750. };
  10751. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  10752. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  10753. texture.baseWidth = width;
  10754. texture.baseHeight = height;
  10755. if (generateMipMaps) {
  10756. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  10757. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  10758. }
  10759. // this.resetTextureCache();
  10760. texture.width = width;
  10761. texture.height = height;
  10762. texture.isReady = false;
  10763. texture.generateMipMaps = generateMipMaps;
  10764. texture.samplingMode = samplingMode;
  10765. this.updateTextureSamplingMode(samplingMode, texture);
  10766. this._internalTexturesCache.push(texture);
  10767. return texture;
  10768. };
  10769. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  10770. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  10771. if (texture.isCube) {
  10772. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  10773. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  10774. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  10775. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10776. }
  10777. else if (texture.is3D) {
  10778. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  10779. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  10780. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  10781. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  10782. }
  10783. else {
  10784. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  10785. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  10786. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  10787. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10788. }
  10789. texture.samplingMode = samplingMode;
  10790. };
  10791. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  10792. if (premulAlpha === void 0) { premulAlpha = false; }
  10793. if (!texture) {
  10794. return;
  10795. }
  10796. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  10797. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  10798. if (premulAlpha) {
  10799. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  10800. }
  10801. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  10802. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  10803. if (texture.generateMipMaps) {
  10804. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10805. }
  10806. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10807. if (premulAlpha) {
  10808. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  10809. }
  10810. texture.isReady = true;
  10811. };
  10812. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  10813. if (!texture || texture._isDisabled) {
  10814. return;
  10815. }
  10816. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  10817. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  10818. try {
  10819. // Testing video texture support
  10820. if (this._videoTextureSupported === undefined) {
  10821. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  10822. if (this._gl.getError() !== 0) {
  10823. this._videoTextureSupported = false;
  10824. }
  10825. else {
  10826. this._videoTextureSupported = true;
  10827. }
  10828. }
  10829. // Copy video through the current working canvas if video texture is not supported
  10830. if (!this._videoTextureSupported) {
  10831. if (!texture._workingCanvas) {
  10832. texture._workingCanvas = document.createElement("canvas");
  10833. var context = texture._workingCanvas.getContext("2d");
  10834. if (!context) {
  10835. throw new Error("Unable to get 2d context");
  10836. }
  10837. texture._workingContext = context;
  10838. texture._workingCanvas.width = texture.width;
  10839. texture._workingCanvas.height = texture.height;
  10840. }
  10841. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  10842. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  10843. }
  10844. else {
  10845. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  10846. }
  10847. if (texture.generateMipMaps) {
  10848. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10849. }
  10850. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10851. // this.resetTextureCache();
  10852. texture.isReady = true;
  10853. }
  10854. catch (ex) {
  10855. // Something unexpected
  10856. // Let's disable the texture
  10857. texture._isDisabled = true;
  10858. }
  10859. };
  10860. Engine.prototype.createRenderTargetTexture = function (size, options) {
  10861. var fullOptions = new RenderTargetCreationOptions();
  10862. if (options !== undefined && typeof options === "object") {
  10863. fullOptions.generateMipMaps = options.generateMipMaps;
  10864. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  10865. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  10866. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  10867. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  10868. }
  10869. else {
  10870. fullOptions.generateMipMaps = options;
  10871. fullOptions.generateDepthBuffer = true;
  10872. fullOptions.generateStencilBuffer = false;
  10873. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  10874. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  10875. }
  10876. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  10877. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  10878. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10879. }
  10880. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  10881. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  10882. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10883. }
  10884. var gl = this._gl;
  10885. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  10886. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  10887. var width = size.width || size;
  10888. var height = size.height || size;
  10889. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  10890. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  10891. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  10892. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  10893. }
  10894. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  10895. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  10896. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10897. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10898. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type), width, height, 0, gl.RGBA, this._getWebGLTextureType(fullOptions.type), null);
  10899. // Create the framebuffer
  10900. var framebuffer = gl.createFramebuffer();
  10901. this.bindUnboundFramebuffer(framebuffer);
  10902. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  10903. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  10904. if (fullOptions.generateMipMaps) {
  10905. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10906. }
  10907. // Unbind
  10908. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10909. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10910. this.bindUnboundFramebuffer(null);
  10911. texture._framebuffer = framebuffer;
  10912. texture.baseWidth = width;
  10913. texture.baseHeight = height;
  10914. texture.width = width;
  10915. texture.height = height;
  10916. texture.isReady = true;
  10917. texture.samples = 1;
  10918. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  10919. texture.samplingMode = fullOptions.samplingMode;
  10920. texture.type = fullOptions.type;
  10921. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  10922. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  10923. // this.resetTextureCache();
  10924. this._internalTexturesCache.push(texture);
  10925. return texture;
  10926. };
  10927. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  10928. var generateMipMaps = false;
  10929. var generateDepthBuffer = true;
  10930. var generateStencilBuffer = false;
  10931. var generateDepthTexture = false;
  10932. var textureCount = 1;
  10933. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  10934. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  10935. var types = [], samplingModes = [];
  10936. if (options !== undefined) {
  10937. generateMipMaps = options.generateMipMaps;
  10938. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  10939. generateStencilBuffer = options.generateStencilBuffer;
  10940. generateDepthTexture = options.generateDepthTexture;
  10941. textureCount = options.textureCount || 1;
  10942. if (options.types) {
  10943. types = options.types;
  10944. }
  10945. if (options.samplingModes) {
  10946. samplingModes = options.samplingModes;
  10947. }
  10948. }
  10949. var gl = this._gl;
  10950. // Create the framebuffer
  10951. var framebuffer = gl.createFramebuffer();
  10952. this.bindUnboundFramebuffer(framebuffer);
  10953. var width = size.width || size;
  10954. var height = size.height || size;
  10955. var textures = [];
  10956. var attachments = [];
  10957. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  10958. for (var i = 0; i < textureCount; i++) {
  10959. var samplingMode = samplingModes[i] || defaultSamplingMode;
  10960. var type = types[i] || defaultType;
  10961. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  10962. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  10963. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10964. }
  10965. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  10966. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  10967. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  10968. }
  10969. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  10970. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  10971. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  10972. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  10973. }
  10974. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  10975. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  10976. textures.push(texture);
  10977. attachments.push(attachment);
  10978. gl.activeTexture(gl["TEXTURE" + i]);
  10979. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  10980. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  10981. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  10982. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10983. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10984. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  10985. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  10986. if (generateMipMaps) {
  10987. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  10988. }
  10989. // Unbind
  10990. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10991. texture._framebuffer = framebuffer;
  10992. texture._depthStencilBuffer = depthStencilBuffer;
  10993. texture.baseWidth = width;
  10994. texture.baseHeight = height;
  10995. texture.width = width;
  10996. texture.height = height;
  10997. texture.isReady = true;
  10998. texture.samples = 1;
  10999. texture.generateMipMaps = generateMipMaps;
  11000. texture.samplingMode = samplingMode;
  11001. texture.type = type;
  11002. texture._generateDepthBuffer = generateDepthBuffer;
  11003. texture._generateStencilBuffer = generateStencilBuffer;
  11004. texture._attachments = attachments;
  11005. this._internalTexturesCache.push(texture);
  11006. }
  11007. if (generateDepthTexture && this._caps.depthTextureExtension) {
  11008. // Depth texture
  11009. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  11010. gl.activeTexture(gl.TEXTURE0);
  11011. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  11012. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  11013. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  11014. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  11015. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  11016. 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);
  11017. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  11018. depthTexture._framebuffer = framebuffer;
  11019. depthTexture.baseWidth = width;
  11020. depthTexture.baseHeight = height;
  11021. depthTexture.width = width;
  11022. depthTexture.height = height;
  11023. depthTexture.isReady = true;
  11024. depthTexture.samples = 1;
  11025. depthTexture.generateMipMaps = generateMipMaps;
  11026. depthTexture.samplingMode = gl.NEAREST;
  11027. depthTexture._generateDepthBuffer = generateDepthBuffer;
  11028. depthTexture._generateStencilBuffer = generateStencilBuffer;
  11029. textures.push(depthTexture);
  11030. this._internalTexturesCache.push(depthTexture);
  11031. }
  11032. gl.drawBuffers(attachments);
  11033. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  11034. this.bindUnboundFramebuffer(null);
  11035. this.resetTextureCache();
  11036. return textures;
  11037. };
  11038. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  11039. if (samples === void 0) { samples = 1; }
  11040. var depthStencilBuffer = null;
  11041. var gl = this._gl;
  11042. // Create the depth/stencil buffer
  11043. if (generateStencilBuffer) {
  11044. depthStencilBuffer = gl.createRenderbuffer();
  11045. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  11046. if (samples > 1) {
  11047. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  11048. }
  11049. else {
  11050. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  11051. }
  11052. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  11053. }
  11054. else if (generateDepthBuffer) {
  11055. depthStencilBuffer = gl.createRenderbuffer();
  11056. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  11057. if (samples > 1) {
  11058. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  11059. }
  11060. else {
  11061. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  11062. }
  11063. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  11064. }
  11065. return depthStencilBuffer;
  11066. };
  11067. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  11068. if (this.webGLVersion < 2 || !texture) {
  11069. return 1;
  11070. }
  11071. if (texture.samples === samples) {
  11072. return samples;
  11073. }
  11074. var gl = this._gl;
  11075. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  11076. // Dispose previous render buffers
  11077. if (texture._depthStencilBuffer) {
  11078. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  11079. texture._depthStencilBuffer = null;
  11080. }
  11081. if (texture._MSAAFramebuffer) {
  11082. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  11083. texture._MSAAFramebuffer = null;
  11084. }
  11085. if (texture._MSAARenderBuffer) {
  11086. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  11087. texture._MSAARenderBuffer = null;
  11088. }
  11089. if (samples > 1) {
  11090. var framebuffer = gl.createFramebuffer();
  11091. if (!framebuffer) {
  11092. throw new Error("Unable to create multi sampled framebuffer");
  11093. }
  11094. texture._MSAAFramebuffer = framebuffer;
  11095. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  11096. var colorRenderbuffer = gl.createRenderbuffer();
  11097. if (!colorRenderbuffer) {
  11098. throw new Error("Unable to create multi sampled framebuffer");
  11099. }
  11100. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  11101. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.RGBA8, texture.width, texture.height);
  11102. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  11103. texture._MSAARenderBuffer = colorRenderbuffer;
  11104. }
  11105. else {
  11106. this.bindUnboundFramebuffer(texture._framebuffer);
  11107. }
  11108. texture.samples = samples;
  11109. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  11110. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  11111. this.bindUnboundFramebuffer(null);
  11112. return samples;
  11113. };
  11114. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  11115. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  11116. return 1;
  11117. }
  11118. if (textures[0].samples === samples) {
  11119. return samples;
  11120. }
  11121. var gl = this._gl;
  11122. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  11123. // Dispose previous render buffers
  11124. if (textures[0]._depthStencilBuffer) {
  11125. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  11126. textures[0]._depthStencilBuffer = null;
  11127. }
  11128. if (textures[0]._MSAAFramebuffer) {
  11129. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  11130. textures[0]._MSAAFramebuffer = null;
  11131. }
  11132. for (var i = 0; i < textures.length; i++) {
  11133. if (textures[i]._MSAARenderBuffer) {
  11134. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  11135. textures[i]._MSAARenderBuffer = null;
  11136. }
  11137. }
  11138. if (samples > 1) {
  11139. var framebuffer = gl.createFramebuffer();
  11140. if (!framebuffer) {
  11141. throw new Error("Unable to create multi sampled framebuffer");
  11142. }
  11143. this.bindUnboundFramebuffer(framebuffer);
  11144. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  11145. var attachments = [];
  11146. for (var i = 0; i < textures.length; i++) {
  11147. var texture = textures[i];
  11148. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  11149. var colorRenderbuffer = gl.createRenderbuffer();
  11150. if (!colorRenderbuffer) {
  11151. throw new Error("Unable to create multi sampled framebuffer");
  11152. }
  11153. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  11154. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.RGBA8, texture.width, texture.height);
  11155. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  11156. texture._MSAAFramebuffer = framebuffer;
  11157. texture._MSAARenderBuffer = colorRenderbuffer;
  11158. texture.samples = samples;
  11159. texture._depthStencilBuffer = depthStencilBuffer;
  11160. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  11161. attachments.push(attachment);
  11162. }
  11163. gl.drawBuffers(attachments);
  11164. }
  11165. else {
  11166. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  11167. }
  11168. this.bindUnboundFramebuffer(null);
  11169. return samples;
  11170. };
  11171. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  11172. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  11173. };
  11174. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  11175. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  11176. };
  11177. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  11178. var gl = this._gl;
  11179. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  11180. var generateMipMaps = true;
  11181. var generateDepthBuffer = true;
  11182. var generateStencilBuffer = false;
  11183. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  11184. if (options !== undefined) {
  11185. generateMipMaps = options.generateMipMaps === undefined ? true : options.generateMipMaps;
  11186. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  11187. generateStencilBuffer = (generateDepthBuffer && options.generateStencilBuffer) ? true : false;
  11188. if (options.samplingMode !== undefined) {
  11189. samplingMode = options.samplingMode;
  11190. }
  11191. }
  11192. texture.isCube = true;
  11193. texture.generateMipMaps = generateMipMaps;
  11194. texture.samples = 1;
  11195. texture.samplingMode = samplingMode;
  11196. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  11197. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  11198. for (var face = 0; face < 6; face++) {
  11199. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  11200. }
  11201. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  11202. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  11203. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  11204. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  11205. // Create the framebuffer
  11206. var framebuffer = gl.createFramebuffer();
  11207. this.bindUnboundFramebuffer(framebuffer);
  11208. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, size, size);
  11209. // Mipmaps
  11210. if (texture.generateMipMaps) {
  11211. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  11212. }
  11213. // Unbind
  11214. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  11215. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  11216. this.bindUnboundFramebuffer(null);
  11217. texture._framebuffer = framebuffer;
  11218. texture.width = size;
  11219. texture.height = size;
  11220. texture.isReady = true;
  11221. //this.resetTextureCache();
  11222. this._internalTexturesCache.push(texture);
  11223. return texture;
  11224. };
  11225. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  11226. var _this = this;
  11227. if (onLoad === void 0) { onLoad = null; }
  11228. if (onError === void 0) { onError = null; }
  11229. if (forcedExtension === void 0) { forcedExtension = null; }
  11230. var callback = function (loadData) {
  11231. if (!loadData) {
  11232. if (onLoad) {
  11233. onLoad(null);
  11234. }
  11235. return;
  11236. }
  11237. var texture = loadData.texture;
  11238. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  11239. texture._lodGenerationScale = scale;
  11240. texture._lodGenerationOffset = offset;
  11241. if (_this._caps.textureLOD) {
  11242. // Do not add extra process if texture lod is supported.
  11243. if (onLoad) {
  11244. onLoad(texture);
  11245. }
  11246. return;
  11247. }
  11248. var mipSlices = 3;
  11249. var gl = _this._gl;
  11250. var width = loadData.width;
  11251. if (!width) {
  11252. return;
  11253. }
  11254. var textures = [];
  11255. for (var i = 0; i < mipSlices; i++) {
  11256. //compute LOD from even spacing in smoothness (matching shader calculation)
  11257. var smoothness = i / (mipSlices - 1);
  11258. var roughness = 1 - smoothness;
  11259. var minLODIndex = offset; // roughness = 0
  11260. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  11261. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  11262. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  11263. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  11264. glTextureFromLod.isCube = true;
  11265. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  11266. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  11267. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  11268. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  11269. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  11270. if (loadData.isDDS) {
  11271. var info = loadData.info;
  11272. var data = loadData.data;
  11273. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  11274. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  11275. }
  11276. else {
  11277. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  11278. }
  11279. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  11280. // Wrap in a base texture for easy binding.
  11281. var lodTexture = new BABYLON.BaseTexture(scene);
  11282. lodTexture.isCube = true;
  11283. lodTexture._texture = glTextureFromLod;
  11284. glTextureFromLod.isReady = true;
  11285. textures.push(lodTexture);
  11286. }
  11287. texture._lodTextureHigh = textures[2];
  11288. texture._lodTextureMid = textures[1];
  11289. texture._lodTextureLow = textures[0];
  11290. if (onLoad) {
  11291. onLoad(texture);
  11292. }
  11293. };
  11294. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  11295. };
  11296. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  11297. var _this = this;
  11298. if (onLoad === void 0) { onLoad = null; }
  11299. if (onError === void 0) { onError = null; }
  11300. if (forcedExtension === void 0) { forcedExtension = null; }
  11301. var gl = this._gl;
  11302. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  11303. texture.isCube = true;
  11304. texture.url = rootUrl;
  11305. texture.generateMipMaps = !noMipmap;
  11306. if (!this._doNotHandleContextLost) {
  11307. texture._extension = forcedExtension;
  11308. texture._files = files;
  11309. }
  11310. var isKTX = false;
  11311. var isDDS = false;
  11312. var lastDot = rootUrl.lastIndexOf('.');
  11313. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  11314. if (this._textureFormatInUse) {
  11315. extension = this._textureFormatInUse;
  11316. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  11317. isKTX = true;
  11318. }
  11319. else {
  11320. isDDS = (extension === ".dds");
  11321. }
  11322. var onerror = function (request, exception) {
  11323. if (onError && request) {
  11324. onError(request.status + " " + request.statusText, exception);
  11325. }
  11326. };
  11327. if (isKTX) {
  11328. this._loadFile(rootUrl, function (data) {
  11329. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 6);
  11330. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  11331. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  11332. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  11333. ktx.uploadLevels(_this._gl, !noMipmap);
  11334. _this.setCubeMapTextureParams(gl, loadMipmap);
  11335. texture.width = ktx.pixelWidth;
  11336. texture.height = ktx.pixelHeight;
  11337. texture.isReady = true;
  11338. }, undefined, undefined, true, onerror);
  11339. }
  11340. else if (isDDS) {
  11341. if (files && files.length === 6) {
  11342. this._cascadeLoadFiles(rootUrl, scene, function (imgs) {
  11343. var info;
  11344. var loadMipmap = false;
  11345. var width = 0;
  11346. for (var index = 0; index < imgs.length; index++) {
  11347. var data = imgs[index];
  11348. info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  11349. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  11350. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  11351. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  11352. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  11353. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  11354. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  11355. }
  11356. texture.width = info.width;
  11357. texture.height = info.height;
  11358. texture.type = info.textureType;
  11359. width = info.width;
  11360. }
  11361. _this.setCubeMapTextureParams(gl, loadMipmap);
  11362. texture.isReady = true;
  11363. if (onLoad) {
  11364. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  11365. }
  11366. }, files, onError);
  11367. }
  11368. else {
  11369. this._loadFile(rootUrl, function (data) {
  11370. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  11371. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  11372. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  11373. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  11374. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  11375. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  11376. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  11377. }
  11378. _this.setCubeMapTextureParams(gl, loadMipmap);
  11379. texture.width = info.width;
  11380. texture.height = info.height;
  11381. texture.isReady = true;
  11382. texture.type = info.textureType;
  11383. if (onLoad) {
  11384. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  11385. }
  11386. }, undefined, undefined, true, onerror);
  11387. }
  11388. }
  11389. else {
  11390. if (!files) {
  11391. throw new Error("Cannot load cubemap because files were not defined");
  11392. }
  11393. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  11394. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  11395. var height = width;
  11396. _this._prepareWorkingCanvas();
  11397. if (!_this._workingCanvas || !_this._workingContext) {
  11398. return;
  11399. }
  11400. _this._workingCanvas.width = width;
  11401. _this._workingCanvas.height = height;
  11402. var faces = [
  11403. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  11404. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  11405. ];
  11406. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  11407. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  11408. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  11409. for (var index = 0; index < faces.length; index++) {
  11410. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  11411. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  11412. }
  11413. if (!noMipmap) {
  11414. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  11415. }
  11416. _this.setCubeMapTextureParams(gl, !noMipmap);
  11417. texture.width = width;
  11418. texture.height = height;
  11419. texture.isReady = true;
  11420. if (format) {
  11421. texture.format = format;
  11422. }
  11423. texture.onLoadedObservable.notifyObservers(texture);
  11424. texture.onLoadedObservable.clear();
  11425. if (onLoad) {
  11426. onLoad();
  11427. }
  11428. }, files, onError);
  11429. }
  11430. this._internalTexturesCache.push(texture);
  11431. return texture;
  11432. };
  11433. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  11434. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  11435. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  11436. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  11437. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  11438. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  11439. // this.resetTextureCache();
  11440. };
  11441. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  11442. if (compression === void 0) { compression = null; }
  11443. if (level === void 0) { level = 0; }
  11444. texture._bufferViewArray = data;
  11445. texture.format = format;
  11446. texture.type = type;
  11447. texture.invertY = invertY;
  11448. texture._compression = compression;
  11449. var gl = this._gl;
  11450. var textureType = this._getWebGLTextureType(type);
  11451. var internalFormat = this._getInternalFormat(format);
  11452. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  11453. var needConversion = false;
  11454. if (internalFormat === gl.RGB) {
  11455. internalFormat = gl.RGBA;
  11456. needConversion = true;
  11457. }
  11458. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  11459. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  11460. if (texture.width % 4 !== 0) {
  11461. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  11462. }
  11463. // Data are known to be in +X +Y +Z -X -Y -Z
  11464. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  11465. var faceData = data[faceIndex];
  11466. if (compression) {
  11467. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  11468. }
  11469. else {
  11470. if (needConversion) {
  11471. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  11472. }
  11473. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  11474. }
  11475. }
  11476. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  11477. if (isPot && texture.generateMipMaps && level === 0) {
  11478. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  11479. }
  11480. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  11481. // this.resetTextureCache();
  11482. texture.isReady = true;
  11483. };
  11484. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  11485. if (compression === void 0) { compression = null; }
  11486. var gl = this._gl;
  11487. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  11488. texture.isCube = true;
  11489. texture.generateMipMaps = generateMipMaps;
  11490. texture.format = format;
  11491. texture.type = type;
  11492. if (!this._doNotHandleContextLost) {
  11493. texture._bufferViewArray = data;
  11494. }
  11495. var textureType = this._getWebGLTextureType(type);
  11496. var internalFormat = this._getInternalFormat(format);
  11497. if (internalFormat === gl.RGB) {
  11498. internalFormat = gl.RGBA;
  11499. }
  11500. var width = size;
  11501. var height = width;
  11502. texture.width = width;
  11503. texture.height = height;
  11504. // Double check on POT to generate Mips.
  11505. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  11506. if (!isPot) {
  11507. generateMipMaps = false;
  11508. }
  11509. // Upload data if needed. The texture won't be ready until then.
  11510. if (data) {
  11511. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  11512. }
  11513. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  11514. // Filters
  11515. if (data && generateMipMaps) {
  11516. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  11517. }
  11518. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  11519. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  11520. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  11521. }
  11522. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  11523. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  11524. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  11525. }
  11526. else {
  11527. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  11528. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  11529. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  11530. }
  11531. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  11532. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  11533. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  11534. return texture;
  11535. };
  11536. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  11537. var _this = this;
  11538. if (onLoad === void 0) { onLoad = null; }
  11539. if (onError === void 0) { onError = null; }
  11540. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  11541. if (invertY === void 0) { invertY = false; }
  11542. var gl = this._gl;
  11543. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  11544. scene._addPendingData(texture);
  11545. texture.url = url;
  11546. this._internalTexturesCache.push(texture);
  11547. var onerror = function (request, exception) {
  11548. scene._removePendingData(texture);
  11549. if (onError && request) {
  11550. onError(request.status + " " + request.statusText, exception);
  11551. }
  11552. };
  11553. var internalCallback = function (data) {
  11554. var width = texture.width;
  11555. var faceDataArrays = callback(data);
  11556. if (!faceDataArrays) {
  11557. return;
  11558. }
  11559. if (mipmmapGenerator) {
  11560. var textureType = _this._getWebGLTextureType(type);
  11561. var internalFormat = _this._getInternalFormat(format);
  11562. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  11563. var needConversion = false;
  11564. if (internalFormat === gl.RGB) {
  11565. internalFormat = gl.RGBA;
  11566. needConversion = true;
  11567. }
  11568. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  11569. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  11570. var mipData = mipmmapGenerator(faceDataArrays);
  11571. for (var level = 0; level < mipData.length; level++) {
  11572. var mipSize = width >> level;
  11573. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  11574. var mipFaceData = mipData[level][faceIndex];
  11575. if (needConversion) {
  11576. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  11577. }
  11578. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  11579. }
  11580. }
  11581. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  11582. }
  11583. else {
  11584. texture.generateMipMaps = !noMipmap;
  11585. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  11586. }
  11587. texture.isReady = true;
  11588. // this.resetTextureCache();
  11589. scene._removePendingData(texture);
  11590. if (onLoad) {
  11591. onLoad();
  11592. }
  11593. };
  11594. this._loadFile(url, function (data) {
  11595. internalCallback(data);
  11596. }, undefined, scene.database, true, onerror);
  11597. return texture;
  11598. };
  11599. ;
  11600. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  11601. if (compression === void 0) { compression = null; }
  11602. var internalFormat = this._getInternalFormat(format);
  11603. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  11604. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  11605. if (!this._doNotHandleContextLost) {
  11606. texture._bufferView = data;
  11607. texture.format = format;
  11608. texture.invertY = invertY;
  11609. texture._compression = compression;
  11610. }
  11611. if (texture.width % 4 !== 0) {
  11612. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  11613. }
  11614. if (compression && data) {
  11615. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  11616. }
  11617. else {
  11618. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  11619. }
  11620. if (texture.generateMipMaps) {
  11621. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  11622. }
  11623. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  11624. // this.resetTextureCache();
  11625. texture.isReady = true;
  11626. };
  11627. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  11628. if (compression === void 0) { compression = null; }
  11629. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  11630. texture.baseWidth = width;
  11631. texture.baseHeight = height;
  11632. texture.baseDepth = depth;
  11633. texture.width = width;
  11634. texture.height = height;
  11635. texture.depth = depth;
  11636. texture.format = format;
  11637. texture.generateMipMaps = generateMipMaps;
  11638. texture.samplingMode = samplingMode;
  11639. texture.is3D = true;
  11640. if (!this._doNotHandleContextLost) {
  11641. texture._bufferView = data;
  11642. }
  11643. this.updateRawTexture3D(texture, data, format, invertY, compression);
  11644. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  11645. // Filters
  11646. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  11647. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  11648. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  11649. if (generateMipMaps) {
  11650. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  11651. }
  11652. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  11653. this._internalTexturesCache.push(texture);
  11654. return texture;
  11655. };
  11656. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  11657. var gl = this._gl;
  11658. if (!gl) {
  11659. return;
  11660. }
  11661. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  11662. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  11663. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  11664. if (!noMipmap && !isCompressed) {
  11665. gl.generateMipmap(gl.TEXTURE_2D);
  11666. }
  11667. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  11668. // this.resetTextureCache();
  11669. if (scene) {
  11670. scene._removePendingData(texture);
  11671. }
  11672. texture.onLoadedObservable.notifyObservers(texture);
  11673. texture.onLoadedObservable.clear();
  11674. };
  11675. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  11676. var _this = this;
  11677. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  11678. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  11679. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  11680. var gl = this._gl;
  11681. if (!gl) {
  11682. return;
  11683. }
  11684. if (!texture._webGLTexture) {
  11685. // this.resetTextureCache();
  11686. if (scene) {
  11687. scene._removePendingData(texture);
  11688. }
  11689. return;
  11690. }
  11691. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  11692. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  11693. texture.baseWidth = width;
  11694. texture.baseHeight = height;
  11695. texture.width = potWidth;
  11696. texture.height = potHeight;
  11697. texture.isReady = true;
  11698. if (processFunction(potWidth, potHeight, function () {
  11699. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  11700. })) {
  11701. // Returning as texture needs extra async steps
  11702. return;
  11703. }
  11704. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  11705. };
  11706. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  11707. // Create new RGBA data container.
  11708. var rgbaData;
  11709. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  11710. rgbaData = new Float32Array(width * height * 4);
  11711. }
  11712. else {
  11713. rgbaData = new Uint32Array(width * height * 4);
  11714. }
  11715. // Convert each pixel.
  11716. for (var x = 0; x < width; x++) {
  11717. for (var y = 0; y < height; y++) {
  11718. var index = (y * width + x) * 3;
  11719. var newIndex = (y * width + x) * 4;
  11720. // Map Old Value to new value.
  11721. rgbaData[newIndex + 0] = rgbData[index + 0];
  11722. rgbaData[newIndex + 1] = rgbData[index + 1];
  11723. rgbaData[newIndex + 2] = rgbData[index + 2];
  11724. // Add fully opaque alpha channel.
  11725. rgbaData[newIndex + 3] = 1;
  11726. }
  11727. }
  11728. return rgbaData;
  11729. };
  11730. Engine.prototype._releaseFramebufferObjects = function (texture) {
  11731. var gl = this._gl;
  11732. if (texture._framebuffer) {
  11733. gl.deleteFramebuffer(texture._framebuffer);
  11734. texture._framebuffer = null;
  11735. }
  11736. if (texture._depthStencilBuffer) {
  11737. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  11738. texture._depthStencilBuffer = null;
  11739. }
  11740. if (texture._MSAAFramebuffer) {
  11741. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  11742. texture._MSAAFramebuffer = null;
  11743. }
  11744. if (texture._MSAARenderBuffer) {
  11745. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  11746. texture._MSAARenderBuffer = null;
  11747. }
  11748. };
  11749. Engine.prototype._releaseTexture = function (texture) {
  11750. var gl = this._gl;
  11751. this._releaseFramebufferObjects(texture);
  11752. gl.deleteTexture(texture._webGLTexture);
  11753. // Unbind channels
  11754. this.unbindAllTextures();
  11755. var index = this._internalTexturesCache.indexOf(texture);
  11756. if (index !== -1) {
  11757. this._internalTexturesCache.splice(index, 1);
  11758. }
  11759. // Integrated fixed lod samplers.
  11760. if (texture._lodTextureHigh) {
  11761. texture._lodTextureHigh.dispose();
  11762. }
  11763. if (texture._lodTextureMid) {
  11764. texture._lodTextureMid.dispose();
  11765. }
  11766. if (texture._lodTextureLow) {
  11767. texture._lodTextureLow.dispose();
  11768. }
  11769. };
  11770. Engine.prototype.setProgram = function (program) {
  11771. if (this._currentProgram !== program) {
  11772. this._gl.useProgram(program);
  11773. this._currentProgram = program;
  11774. }
  11775. };
  11776. Engine.prototype.bindSamplers = function (effect) {
  11777. this.setProgram(effect.getProgram());
  11778. var samplers = effect.getSamplers();
  11779. for (var index = 0; index < samplers.length; index++) {
  11780. var uniform = effect.getUniform(samplers[index]);
  11781. if (uniform) {
  11782. this._boundUniforms[index] = uniform;
  11783. }
  11784. }
  11785. this._currentEffect = null;
  11786. };
  11787. Engine.prototype._activateTextureChannel = function (channel) {
  11788. if (this._activeChannel !== channel && channel > -1) {
  11789. this._gl.activeTexture(this._gl.TEXTURE0 + channel);
  11790. this._activeChannel = channel;
  11791. }
  11792. };
  11793. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  11794. var index = this._boundTexturesStack.indexOf(internalTexture);
  11795. if (index > -1 && index !== this._boundTexturesStack.length - 1) {
  11796. this._boundTexturesStack.splice(index, 1);
  11797. this._boundTexturesStack.push(internalTexture);
  11798. }
  11799. };
  11800. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  11801. var currentSlot = internalTexture._designatedSlot;
  11802. internalTexture._designatedSlot = -1;
  11803. var index = this._boundTexturesStack.indexOf(internalTexture);
  11804. if (index > -1) {
  11805. this._boundTexturesStack.splice(index, 1);
  11806. if (currentSlot > -1) {
  11807. this._boundTexturesCache[currentSlot] = null;
  11808. this._nextFreeTextureSlots.push(currentSlot);
  11809. }
  11810. }
  11811. return currentSlot;
  11812. };
  11813. Engine.prototype._bindTextureDirectly = function (target, texture, doNotBindUniformToTextureChannel) {
  11814. if (doNotBindUniformToTextureChannel === void 0) { doNotBindUniformToTextureChannel = false; }
  11815. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  11816. var isTextureForRendering = texture && texture._initialSlot > -1;
  11817. if (currentTextureBound !== texture) {
  11818. if (currentTextureBound) {
  11819. this._removeDesignatedSlot(currentTextureBound);
  11820. }
  11821. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  11822. if (this._activeChannel >= 0) {
  11823. this._boundTexturesCache[this._activeChannel] = texture;
  11824. if (isTextureForRendering) {
  11825. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  11826. if (slotIndex > -1) {
  11827. this._nextFreeTextureSlots.splice(slotIndex, 1);
  11828. }
  11829. this._boundTexturesStack.push(texture);
  11830. }
  11831. }
  11832. }
  11833. if (isTextureForRendering && this._activeChannel > -1) {
  11834. texture._designatedSlot = this._activeChannel;
  11835. if (!doNotBindUniformToTextureChannel) {
  11836. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  11837. }
  11838. }
  11839. };
  11840. Engine.prototype._bindTexture = function (channel, texture) {
  11841. if (channel < 0) {
  11842. return;
  11843. }
  11844. if (texture) {
  11845. channel = this._getCorrectTextureChannel(channel, texture);
  11846. }
  11847. this._activateTextureChannel(channel);
  11848. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  11849. };
  11850. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  11851. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  11852. };
  11853. Engine.prototype.unbindAllTextures = function () {
  11854. for (var channel = 0; channel < this._caps.maxCombinedTexturesImageUnits; channel++) {
  11855. this._activateTextureChannel(channel);
  11856. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11857. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  11858. if (this.webGLVersion > 1) {
  11859. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  11860. }
  11861. }
  11862. };
  11863. Engine.prototype.setTexture = function (channel, uniform, texture) {
  11864. if (channel < 0) {
  11865. return;
  11866. }
  11867. if (uniform) {
  11868. this._boundUniforms[channel] = uniform;
  11869. }
  11870. this._setTexture(channel, texture);
  11871. };
  11872. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  11873. if (!internalTexture) {
  11874. return -1;
  11875. }
  11876. internalTexture._initialSlot = channel;
  11877. if (channel !== internalTexture._designatedSlot) {
  11878. if (internalTexture._designatedSlot > -1) {
  11879. return internalTexture._designatedSlot;
  11880. }
  11881. else {
  11882. // No slot for this texture, let's pick a new one (if we find a free slot)
  11883. if (this._nextFreeTextureSlots.length) {
  11884. return this._nextFreeTextureSlots[0];
  11885. }
  11886. // We need to recycle the oldest bound texture, sorry.
  11887. this._textureCollisions.addCount(1, false);
  11888. return this._removeDesignatedSlot(this._boundTexturesStack[0]);
  11889. }
  11890. }
  11891. return channel;
  11892. };
  11893. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  11894. var uniform = this._boundUniforms[sourceSlot];
  11895. this._gl.uniform1i(uniform, destination);
  11896. };
  11897. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray) {
  11898. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  11899. // Not ready?
  11900. if (!texture) {
  11901. if (this._boundTexturesCache[channel] != null) {
  11902. this._activateTextureChannel(channel);
  11903. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  11904. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  11905. if (this.webGLVersion > 1) {
  11906. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  11907. }
  11908. }
  11909. return false;
  11910. }
  11911. // Video
  11912. var alreadyActivated = false;
  11913. if (texture.video) {
  11914. this._activateTextureChannel(channel);
  11915. alreadyActivated = true;
  11916. texture.update();
  11917. }
  11918. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  11919. texture.delayLoad();
  11920. return false;
  11921. }
  11922. var internalTexture;
  11923. if (texture.isReady()) {
  11924. internalTexture = texture.getInternalTexture();
  11925. }
  11926. else if (texture.isCube) {
  11927. internalTexture = this.emptyCubeTexture;
  11928. }
  11929. else if (texture.is3D) {
  11930. internalTexture = this.emptyTexture3D;
  11931. }
  11932. else {
  11933. internalTexture = this.emptyTexture;
  11934. }
  11935. if (!isPartOfTextureArray) {
  11936. channel = this._getCorrectTextureChannel(channel, internalTexture);
  11937. }
  11938. if (this._boundTexturesCache[channel] === internalTexture) {
  11939. this._moveBoundTextureOnTop(internalTexture);
  11940. if (!isPartOfTextureArray) {
  11941. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  11942. }
  11943. return false;
  11944. }
  11945. if (!alreadyActivated) {
  11946. this._activateTextureChannel(channel);
  11947. }
  11948. if (internalTexture && internalTexture.is3D) {
  11949. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  11950. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  11951. internalTexture._cachedWrapU = texture.wrapU;
  11952. switch (texture.wrapU) {
  11953. case BABYLON.Texture.WRAP_ADDRESSMODE:
  11954. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  11955. break;
  11956. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  11957. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  11958. break;
  11959. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  11960. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  11961. break;
  11962. }
  11963. }
  11964. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  11965. internalTexture._cachedWrapV = texture.wrapV;
  11966. switch (texture.wrapV) {
  11967. case BABYLON.Texture.WRAP_ADDRESSMODE:
  11968. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  11969. break;
  11970. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  11971. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  11972. break;
  11973. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  11974. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  11975. break;
  11976. }
  11977. }
  11978. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  11979. internalTexture._cachedWrapR = texture.wrapR;
  11980. switch (texture.wrapV) {
  11981. case BABYLON.Texture.WRAP_ADDRESSMODE:
  11982. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.REPEAT);
  11983. break;
  11984. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  11985. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.CLAMP_TO_EDGE);
  11986. break;
  11987. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  11988. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.MIRRORED_REPEAT);
  11989. break;
  11990. }
  11991. }
  11992. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  11993. }
  11994. else if (internalTexture && internalTexture.isCube) {
  11995. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  11996. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  11997. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  11998. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  11999. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  12000. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  12001. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  12002. }
  12003. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  12004. }
  12005. else {
  12006. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  12007. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  12008. internalTexture._cachedWrapU = texture.wrapU;
  12009. switch (texture.wrapU) {
  12010. case BABYLON.Texture.WRAP_ADDRESSMODE:
  12011. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  12012. break;
  12013. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  12014. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  12015. break;
  12016. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  12017. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  12018. break;
  12019. }
  12020. }
  12021. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  12022. internalTexture._cachedWrapV = texture.wrapV;
  12023. switch (texture.wrapV) {
  12024. case BABYLON.Texture.WRAP_ADDRESSMODE:
  12025. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  12026. break;
  12027. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  12028. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  12029. break;
  12030. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  12031. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  12032. break;
  12033. }
  12034. }
  12035. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  12036. }
  12037. return true;
  12038. };
  12039. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  12040. if (channel < 0 || !uniform) {
  12041. return;
  12042. }
  12043. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  12044. this._textureUnits = new Int32Array(textures.length);
  12045. }
  12046. for (var i = 0; i < textures.length; i++) {
  12047. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  12048. }
  12049. this._gl.uniform1iv(uniform, this._textureUnits);
  12050. for (var index = 0; index < textures.length; index++) {
  12051. this._setTexture(this._textureUnits[index], textures[index], true);
  12052. }
  12053. };
  12054. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  12055. var internalTexture = texture.getInternalTexture();
  12056. if (!internalTexture) {
  12057. return;
  12058. }
  12059. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  12060. var value = texture.anisotropicFilteringLevel;
  12061. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  12062. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  12063. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  12064. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  12065. }
  12066. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  12067. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  12068. internalTexture._cachedAnisotropicFilteringLevel = value;
  12069. }
  12070. };
  12071. Engine.prototype.readPixels = function (x, y, width, height) {
  12072. var data = new Uint8Array(height * width * 4);
  12073. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  12074. return data;
  12075. };
  12076. /**
  12077. * Add an externaly attached data from its key.
  12078. * This method call will fail and return false, if such key already exists.
  12079. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  12080. * @param key the unique key that identifies the data
  12081. * @param data the data object to associate to the key for this Engine instance
  12082. * @return true if no such key were already present and the data was added successfully, false otherwise
  12083. */
  12084. Engine.prototype.addExternalData = function (key, data) {
  12085. if (!this._externalData) {
  12086. this._externalData = new BABYLON.StringDictionary();
  12087. }
  12088. return this._externalData.add(key, data);
  12089. };
  12090. /**
  12091. * Get an externaly attached data from its key
  12092. * @param key the unique key that identifies the data
  12093. * @return the associated data, if present (can be null), or undefined if not present
  12094. */
  12095. Engine.prototype.getExternalData = function (key) {
  12096. if (!this._externalData) {
  12097. this._externalData = new BABYLON.StringDictionary();
  12098. }
  12099. return this._externalData.get(key);
  12100. };
  12101. /**
  12102. * Get an externaly attached data from its key, create it using a factory if it's not already present
  12103. * @param key the unique key that identifies the data
  12104. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  12105. * @return the associated data, can be null if the factory returned null.
  12106. */
  12107. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  12108. if (!this._externalData) {
  12109. this._externalData = new BABYLON.StringDictionary();
  12110. }
  12111. return this._externalData.getOrAddWithFactory(key, factory);
  12112. };
  12113. /**
  12114. * Remove an externaly attached data from the Engine instance
  12115. * @param key the unique key that identifies the data
  12116. * @return true if the data was successfully removed, false if it doesn't exist
  12117. */
  12118. Engine.prototype.removeExternalData = function (key) {
  12119. if (!this._externalData) {
  12120. this._externalData = new BABYLON.StringDictionary();
  12121. }
  12122. return this._externalData.remove(key);
  12123. };
  12124. Engine.prototype.unbindAllAttributes = function () {
  12125. if (this._mustWipeVertexAttributes) {
  12126. this._mustWipeVertexAttributes = false;
  12127. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  12128. this._gl.disableVertexAttribArray(i);
  12129. this._vertexAttribArraysEnabled[i] = false;
  12130. this._currentBufferPointers[i].active = false;
  12131. }
  12132. return;
  12133. }
  12134. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  12135. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  12136. continue;
  12137. }
  12138. this._gl.disableVertexAttribArray(i);
  12139. this._vertexAttribArraysEnabled[i] = false;
  12140. this._currentBufferPointers[i].active = false;
  12141. }
  12142. };
  12143. Engine.prototype.releaseEffects = function () {
  12144. for (var name in this._compiledEffects) {
  12145. this._deleteProgram(this._compiledEffects[name]._program);
  12146. }
  12147. this._compiledEffects = {};
  12148. };
  12149. // Dispose
  12150. Engine.prototype.dispose = function () {
  12151. this.hideLoadingUI();
  12152. this.stopRenderLoop();
  12153. // Release postProcesses
  12154. while (this.postProcesses.length) {
  12155. this.postProcesses[0].dispose();
  12156. }
  12157. // Empty texture
  12158. if (this._emptyTexture) {
  12159. this._releaseTexture(this._emptyTexture);
  12160. this._emptyTexture = null;
  12161. }
  12162. if (this._emptyCubeTexture) {
  12163. this._releaseTexture(this._emptyCubeTexture);
  12164. this._emptyCubeTexture = null;
  12165. }
  12166. // Rescale PP
  12167. if (this._rescalePostProcess) {
  12168. this._rescalePostProcess.dispose();
  12169. }
  12170. // Release scenes
  12171. while (this.scenes.length) {
  12172. this.scenes[0].dispose();
  12173. }
  12174. // Release audio engine
  12175. if (Engine.audioEngine) {
  12176. Engine.audioEngine.dispose();
  12177. }
  12178. // Release effects
  12179. this.releaseEffects();
  12180. // Unbind
  12181. this.unbindAllAttributes();
  12182. if (this._dummyFramebuffer) {
  12183. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  12184. }
  12185. //WebVR
  12186. this.disableVR();
  12187. // Events
  12188. if (BABYLON.Tools.IsWindowObjectExist()) {
  12189. window.removeEventListener("blur", this._onBlur);
  12190. window.removeEventListener("focus", this._onFocus);
  12191. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  12192. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  12193. if (this._renderingCanvas) {
  12194. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  12195. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  12196. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasBlur);
  12197. if (!this._doNotHandleContextLost) {
  12198. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  12199. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  12200. }
  12201. }
  12202. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  12203. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  12204. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  12205. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  12206. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  12207. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  12208. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  12209. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  12210. if (this._onVrDisplayConnect) {
  12211. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  12212. if (this._onVrDisplayDisconnect) {
  12213. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  12214. }
  12215. if (this._onVrDisplayPresentChange) {
  12216. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  12217. }
  12218. this._onVrDisplayConnect = null;
  12219. this._onVrDisplayDisconnect = null;
  12220. }
  12221. }
  12222. // Remove from Instances
  12223. var index = Engine.Instances.indexOf(this);
  12224. if (index >= 0) {
  12225. Engine.Instances.splice(index, 1);
  12226. }
  12227. this._workingCanvas = null;
  12228. this._workingContext = null;
  12229. this._currentBufferPointers = [];
  12230. this._renderingCanvas = null;
  12231. this._currentProgram = null;
  12232. this.onResizeObservable.clear();
  12233. this.onCanvasBlurObservable.clear();
  12234. this.onCanvasFocusObservable.clear();
  12235. this.onCanvasPointerOutObservable.clear();
  12236. this.onBeginFrameObservable.clear();
  12237. this.onEndFrameObservable.clear();
  12238. BABYLON.Effect.ResetCache();
  12239. // Abort active requests
  12240. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  12241. var request = _a[_i];
  12242. request.abort();
  12243. }
  12244. };
  12245. // Loading screen
  12246. Engine.prototype.displayLoadingUI = function () {
  12247. if (!BABYLON.Tools.IsWindowObjectExist()) {
  12248. return;
  12249. }
  12250. var loadingScreen = this.loadingScreen;
  12251. if (loadingScreen) {
  12252. loadingScreen.displayLoadingUI();
  12253. }
  12254. };
  12255. Engine.prototype.hideLoadingUI = function () {
  12256. if (!BABYLON.Tools.IsWindowObjectExist()) {
  12257. return;
  12258. }
  12259. var loadingScreen = this.loadingScreen;
  12260. if (loadingScreen) {
  12261. loadingScreen.hideLoadingUI();
  12262. }
  12263. };
  12264. Object.defineProperty(Engine.prototype, "loadingScreen", {
  12265. get: function () {
  12266. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  12267. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  12268. return this._loadingScreen;
  12269. },
  12270. set: function (loadingScreen) {
  12271. this._loadingScreen = loadingScreen;
  12272. },
  12273. enumerable: true,
  12274. configurable: true
  12275. });
  12276. Object.defineProperty(Engine.prototype, "loadingUIText", {
  12277. set: function (text) {
  12278. this.loadingScreen.loadingUIText = text;
  12279. },
  12280. enumerable: true,
  12281. configurable: true
  12282. });
  12283. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  12284. set: function (color) {
  12285. this.loadingScreen.loadingUIBackgroundColor = color;
  12286. },
  12287. enumerable: true,
  12288. configurable: true
  12289. });
  12290. Engine.prototype.attachContextLostEvent = function (callback) {
  12291. if (this._renderingCanvas) {
  12292. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  12293. }
  12294. };
  12295. Engine.prototype.attachContextRestoredEvent = function (callback) {
  12296. if (this._renderingCanvas) {
  12297. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  12298. }
  12299. };
  12300. Engine.prototype.getVertexShaderSource = function (program) {
  12301. var shaders = this._gl.getAttachedShaders(program);
  12302. if (!shaders) {
  12303. return null;
  12304. }
  12305. return this._gl.getShaderSource(shaders[0]);
  12306. };
  12307. Engine.prototype.getFragmentShaderSource = function (program) {
  12308. var shaders = this._gl.getAttachedShaders(program);
  12309. if (!shaders) {
  12310. return null;
  12311. }
  12312. return this._gl.getShaderSource(shaders[1]);
  12313. };
  12314. Engine.prototype.getError = function () {
  12315. return this._gl.getError();
  12316. };
  12317. // FPS
  12318. Engine.prototype.getFps = function () {
  12319. return this._fps;
  12320. };
  12321. Engine.prototype.getDeltaTime = function () {
  12322. return this._deltaTime;
  12323. };
  12324. Engine.prototype._measureFps = function () {
  12325. this._performanceMonitor.sampleFrame();
  12326. this._fps = this._performanceMonitor.averageFPS;
  12327. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  12328. };
  12329. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  12330. if (faceIndex === void 0) { faceIndex = -1; }
  12331. var gl = this._gl;
  12332. if (!this._dummyFramebuffer) {
  12333. var dummy = gl.createFramebuffer();
  12334. if (!dummy) {
  12335. throw new Error("Unable to create dummy framebuffer");
  12336. }
  12337. this._dummyFramebuffer = dummy;
  12338. }
  12339. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  12340. if (faceIndex > -1) {
  12341. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  12342. }
  12343. else {
  12344. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  12345. }
  12346. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  12347. var buffer;
  12348. switch (readType) {
  12349. case gl.UNSIGNED_BYTE:
  12350. buffer = new Uint8Array(4 * width * height);
  12351. readType = gl.UNSIGNED_BYTE;
  12352. break;
  12353. default:
  12354. buffer = new Float32Array(4 * width * height);
  12355. readType = gl.FLOAT;
  12356. break;
  12357. }
  12358. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  12359. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  12360. return buffer;
  12361. };
  12362. Engine.prototype._canRenderToFloatFramebuffer = function () {
  12363. if (this._webGLVersion > 1) {
  12364. return this._caps.colorBufferFloat;
  12365. }
  12366. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  12367. };
  12368. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  12369. if (this._webGLVersion > 1) {
  12370. return this._caps.colorBufferFloat;
  12371. }
  12372. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  12373. };
  12374. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  12375. Engine.prototype._canRenderToFramebuffer = function (type) {
  12376. var gl = this._gl;
  12377. //clear existing errors
  12378. while (gl.getError() !== gl.NO_ERROR) { }
  12379. var successful = true;
  12380. var texture = gl.createTexture();
  12381. gl.bindTexture(gl.TEXTURE_2D, texture);
  12382. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  12383. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  12384. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  12385. var fb = gl.createFramebuffer();
  12386. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  12387. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  12388. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  12389. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  12390. successful = successful && (gl.getError() === gl.NO_ERROR);
  12391. //try render by clearing frame buffer's color buffer
  12392. if (successful) {
  12393. gl.clear(gl.COLOR_BUFFER_BIT);
  12394. successful = successful && (gl.getError() === gl.NO_ERROR);
  12395. }
  12396. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  12397. if (successful) {
  12398. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  12399. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  12400. var readFormat = gl.RGBA;
  12401. var readType = gl.UNSIGNED_BYTE;
  12402. var buffer = new Uint8Array(4);
  12403. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  12404. successful = successful && (gl.getError() === gl.NO_ERROR);
  12405. }
  12406. //clean up
  12407. gl.deleteTexture(texture);
  12408. gl.deleteFramebuffer(fb);
  12409. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  12410. //clear accumulated errors
  12411. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  12412. return successful;
  12413. };
  12414. Engine.prototype._getWebGLTextureType = function (type) {
  12415. if (type === Engine.TEXTURETYPE_FLOAT) {
  12416. return this._gl.FLOAT;
  12417. }
  12418. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  12419. // Add Half Float Constant.
  12420. return this._gl.HALF_FLOAT_OES;
  12421. }
  12422. return this._gl.UNSIGNED_BYTE;
  12423. };
  12424. ;
  12425. Engine.prototype._getRGBABufferInternalSizedFormat = function (type) {
  12426. if (this._webGLVersion === 1) {
  12427. return this._gl.RGBA;
  12428. }
  12429. if (type === Engine.TEXTURETYPE_FLOAT) {
  12430. return this._gl.RGBA32F;
  12431. }
  12432. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  12433. return this._gl.RGBA16F;
  12434. }
  12435. return this._gl.RGBA;
  12436. };
  12437. ;
  12438. Engine.prototype.createQuery = function () {
  12439. return this._gl.createQuery();
  12440. };
  12441. Engine.prototype.deleteQuery = function (query) {
  12442. this._gl.deleteQuery(query);
  12443. return this;
  12444. };
  12445. Engine.prototype.isQueryResultAvailable = function (query) {
  12446. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  12447. };
  12448. Engine.prototype.getQueryResult = function (query) {
  12449. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  12450. };
  12451. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  12452. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  12453. this._gl.beginQuery(glAlgorithm, query);
  12454. return this;
  12455. };
  12456. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  12457. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  12458. this._gl.endQuery(glAlgorithm);
  12459. return this;
  12460. };
  12461. /* Time queries */
  12462. Engine.prototype._createTimeQuery = function () {
  12463. var timerQuery = this._caps.timerQuery;
  12464. if (timerQuery.createQueryEXT) {
  12465. return timerQuery.createQueryEXT();
  12466. }
  12467. return this.createQuery();
  12468. };
  12469. Engine.prototype._deleteTimeQuery = function (query) {
  12470. var timerQuery = this._caps.timerQuery;
  12471. if (timerQuery.deleteQueryEXT) {
  12472. timerQuery.deleteQueryEXT(query);
  12473. return;
  12474. }
  12475. this.deleteQuery(query);
  12476. };
  12477. Engine.prototype._getTimeQueryResult = function (query) {
  12478. var timerQuery = this._caps.timerQuery;
  12479. if (timerQuery.getQueryObjectEXT) {
  12480. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  12481. }
  12482. return this.getQueryResult(query);
  12483. };
  12484. Engine.prototype._getTimeQueryAvailability = function (query) {
  12485. var timerQuery = this._caps.timerQuery;
  12486. if (timerQuery.getQueryObjectEXT) {
  12487. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  12488. }
  12489. return this.isQueryResultAvailable(query);
  12490. };
  12491. Engine.prototype.startTimeQuery = function () {
  12492. var timerQuery = this._caps.timerQuery;
  12493. if (!timerQuery) {
  12494. return null;
  12495. }
  12496. var token = new BABYLON._TimeToken();
  12497. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  12498. if (this._caps.canUseTimestampForTimerQuery) {
  12499. token._startTimeQuery = this._createTimeQuery();
  12500. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  12501. }
  12502. else {
  12503. if (this._currentNonTimestampToken) {
  12504. return this._currentNonTimestampToken;
  12505. }
  12506. token._timeElapsedQuery = this._createTimeQuery();
  12507. if (timerQuery.beginQueryEXT) {
  12508. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  12509. }
  12510. else {
  12511. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  12512. }
  12513. this._currentNonTimestampToken = token;
  12514. }
  12515. return token;
  12516. };
  12517. Engine.prototype.endTimeQuery = function (token) {
  12518. var timerQuery = this._caps.timerQuery;
  12519. if (!timerQuery || !token) {
  12520. return -1;
  12521. }
  12522. if (this._caps.canUseTimestampForTimerQuery) {
  12523. if (!token._startTimeQuery) {
  12524. return -1;
  12525. }
  12526. if (!token._endTimeQuery) {
  12527. token._endTimeQuery = this._createTimeQuery();
  12528. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  12529. }
  12530. }
  12531. else if (!token._timeElapsedQueryEnded) {
  12532. if (!token._timeElapsedQuery) {
  12533. return -1;
  12534. }
  12535. if (timerQuery.endQueryEXT) {
  12536. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  12537. }
  12538. else {
  12539. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  12540. }
  12541. token._timeElapsedQueryEnded = true;
  12542. }
  12543. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  12544. var available = false;
  12545. if (token._endTimeQuery) {
  12546. available = this._getTimeQueryAvailability(token._endTimeQuery);
  12547. }
  12548. else if (token._timeElapsedQuery) {
  12549. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  12550. }
  12551. if (available && !disjoint) {
  12552. var result = 0;
  12553. if (this._caps.canUseTimestampForTimerQuery) {
  12554. if (!token._startTimeQuery || !token._endTimeQuery) {
  12555. return -1;
  12556. }
  12557. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  12558. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  12559. result = timeEnd - timeStart;
  12560. this._deleteTimeQuery(token._startTimeQuery);
  12561. this._deleteTimeQuery(token._endTimeQuery);
  12562. token._startTimeQuery = null;
  12563. token._endTimeQuery = null;
  12564. }
  12565. else {
  12566. if (!token._timeElapsedQuery) {
  12567. return -1;
  12568. }
  12569. result = this._getTimeQueryResult(token._timeElapsedQuery);
  12570. this._deleteTimeQuery(token._timeElapsedQuery);
  12571. token._timeElapsedQuery = null;
  12572. token._timeElapsedQueryEnded = false;
  12573. this._currentNonTimestampToken = null;
  12574. }
  12575. return result;
  12576. }
  12577. return -1;
  12578. };
  12579. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  12580. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  12581. };
  12582. // Transform feedback
  12583. Engine.prototype.createTransformFeedback = function () {
  12584. return this._gl.createTransformFeedback();
  12585. };
  12586. Engine.prototype.deleteTransformFeedback = function (value) {
  12587. this._gl.deleteTransformFeedback(value);
  12588. };
  12589. Engine.prototype.bindTransformFeedback = function (value) {
  12590. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  12591. };
  12592. Engine.prototype.beginTransformFeedback = function (usePoints) {
  12593. if (usePoints === void 0) { usePoints = true; }
  12594. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  12595. };
  12596. Engine.prototype.endTransformFeedback = function () {
  12597. this._gl.endTransformFeedback();
  12598. };
  12599. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  12600. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  12601. };
  12602. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  12603. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  12604. };
  12605. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  12606. var _this = this;
  12607. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  12608. this._activeRequests.push(request);
  12609. request.onCompleteObservable.add(function (request) {
  12610. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  12611. });
  12612. return request;
  12613. };
  12614. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  12615. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  12616. var onload = function (data) {
  12617. loadedFiles[index] = data;
  12618. loadedFiles._internalCount++;
  12619. if (loadedFiles._internalCount === 6) {
  12620. onfinish(loadedFiles);
  12621. }
  12622. };
  12623. var onerror = function (request, exception) {
  12624. if (onErrorCallBack && request) {
  12625. onErrorCallBack(request.status + " " + request.statusText, exception);
  12626. }
  12627. };
  12628. this._loadFile(url, onload, undefined, undefined, true, onerror);
  12629. };
  12630. Engine.prototype._cascadeLoadFiles = function (rootUrl, scene, onfinish, files, onError) {
  12631. if (onError === void 0) { onError = null; }
  12632. var loadedFiles = [];
  12633. loadedFiles._internalCount = 0;
  12634. for (var index = 0; index < 6; index++) {
  12635. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  12636. }
  12637. };
  12638. // Statics
  12639. Engine.isSupported = function () {
  12640. try {
  12641. var tempcanvas = document.createElement("canvas");
  12642. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  12643. return gl != null && !!window.WebGLRenderingContext;
  12644. }
  12645. catch (e) {
  12646. return false;
  12647. }
  12648. };
  12649. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  12650. Engine.WebGL2UniformBuffersExceptionList = ["Chrome/63", "Firefox/58"];
  12651. Engine.Instances = new Array();
  12652. // Const statics
  12653. Engine._ALPHA_DISABLE = 0;
  12654. Engine._ALPHA_ADD = 1;
  12655. Engine._ALPHA_COMBINE = 2;
  12656. Engine._ALPHA_SUBTRACT = 3;
  12657. Engine._ALPHA_MULTIPLY = 4;
  12658. Engine._ALPHA_MAXIMIZED = 5;
  12659. Engine._ALPHA_ONEONE = 6;
  12660. Engine._ALPHA_PREMULTIPLIED = 7;
  12661. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  12662. Engine._ALPHA_INTERPOLATE = 9;
  12663. Engine._ALPHA_SCREENMODE = 10;
  12664. Engine._DELAYLOADSTATE_NONE = 0;
  12665. Engine._DELAYLOADSTATE_LOADED = 1;
  12666. Engine._DELAYLOADSTATE_LOADING = 2;
  12667. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  12668. Engine._TEXTUREFORMAT_ALPHA = 0;
  12669. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  12670. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  12671. Engine._TEXTUREFORMAT_RGB = 4;
  12672. Engine._TEXTUREFORMAT_RGBA = 5;
  12673. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  12674. Engine._TEXTURETYPE_FLOAT = 1;
  12675. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  12676. // Depht or Stencil test Constants.
  12677. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  12678. 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.
  12679. 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.
  12680. 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.
  12681. 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.
  12682. 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.
  12683. 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.
  12684. 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.
  12685. // Stencil Actions Constants.
  12686. Engine._KEEP = 0x1E00;
  12687. Engine._REPLACE = 0x1E01;
  12688. Engine._INCR = 0x1E02;
  12689. Engine._DECR = 0x1E03;
  12690. Engine._INVERT = 0x150A;
  12691. Engine._INCR_WRAP = 0x8507;
  12692. Engine._DECR_WRAP = 0x8508;
  12693. // Texture rescaling mode
  12694. Engine._SCALEMODE_FLOOR = 1;
  12695. Engine._SCALEMODE_NEAREST = 2;
  12696. Engine._SCALEMODE_CEILING = 3;
  12697. // Updatable statics so stick with vars here
  12698. Engine.CollisionsEpsilon = 0.001;
  12699. Engine.CodeRepository = "src/";
  12700. Engine.ShadersRepository = "src/Shaders/";
  12701. return Engine;
  12702. }());
  12703. BABYLON.Engine = Engine;
  12704. })(BABYLON || (BABYLON = {}));
  12705. //# sourceMappingURL=babylon.engine.js.map
  12706. var BABYLON;
  12707. (function (BABYLON) {
  12708. /**
  12709. * Node is the basic class for all scene objects (Mesh, Light Camera).
  12710. */
  12711. var Node = /** @class */ (function () {
  12712. /**
  12713. * @constructor
  12714. * @param {string} name - the name and id to be given to this node
  12715. * @param {BABYLON.Scene} the scene this node will be added to
  12716. */
  12717. function Node(name, scene) {
  12718. if (scene === void 0) { scene = null; }
  12719. this.state = "";
  12720. this.metadata = null;
  12721. this.doNotSerialize = false;
  12722. this.animations = new Array();
  12723. this._ranges = {};
  12724. this._isEnabled = true;
  12725. this._isReady = true;
  12726. this._currentRenderId = -1;
  12727. this._parentRenderId = -1;
  12728. /**
  12729. * An event triggered when the mesh is disposed.
  12730. * @type {BABYLON.Observable}
  12731. */
  12732. this.onDisposeObservable = new BABYLON.Observable();
  12733. // Behaviors
  12734. this._behaviors = new Array();
  12735. this.name = name;
  12736. this.id = name;
  12737. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  12738. this.uniqueId = this._scene.getUniqueId();
  12739. this._initCache();
  12740. }
  12741. Object.defineProperty(Node.prototype, "parent", {
  12742. get: function () {
  12743. return this._parentNode;
  12744. },
  12745. set: function (parent) {
  12746. if (this._parentNode === parent) {
  12747. return;
  12748. }
  12749. // Remove self from list of children of parent
  12750. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  12751. var index = this._parentNode._children.indexOf(this);
  12752. if (index !== -1) {
  12753. this._parentNode._children.splice(index, 1);
  12754. }
  12755. }
  12756. // Store new parent
  12757. this._parentNode = parent;
  12758. // Add as child to new parent
  12759. if (this._parentNode) {
  12760. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  12761. this._parentNode._children = new Array();
  12762. }
  12763. this._parentNode._children.push(this);
  12764. }
  12765. },
  12766. enumerable: true,
  12767. configurable: true
  12768. });
  12769. Node.prototype.getClassName = function () {
  12770. return "Node";
  12771. };
  12772. Object.defineProperty(Node.prototype, "onDispose", {
  12773. set: function (callback) {
  12774. if (this._onDisposeObserver) {
  12775. this.onDisposeObservable.remove(this._onDisposeObserver);
  12776. }
  12777. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  12778. },
  12779. enumerable: true,
  12780. configurable: true
  12781. });
  12782. Node.prototype.getScene = function () {
  12783. return this._scene;
  12784. };
  12785. Node.prototype.getEngine = function () {
  12786. return this._scene.getEngine();
  12787. };
  12788. Node.prototype.addBehavior = function (behavior) {
  12789. var _this = this;
  12790. var index = this._behaviors.indexOf(behavior);
  12791. if (index !== -1) {
  12792. return this;
  12793. }
  12794. behavior.init();
  12795. if (this._scene.isLoading) {
  12796. // We defer the attach when the scene will be loaded
  12797. var observer = this._scene.onDataLoadedObservable.add(function () {
  12798. behavior.attach(_this);
  12799. setTimeout(function () {
  12800. // Need to use a timeout to avoid removing an observer while iterating the list of observers
  12801. _this._scene.onDataLoadedObservable.remove(observer);
  12802. }, 0);
  12803. });
  12804. }
  12805. else {
  12806. behavior.attach(this);
  12807. }
  12808. this._behaviors.push(behavior);
  12809. return this;
  12810. };
  12811. Node.prototype.removeBehavior = function (behavior) {
  12812. var index = this._behaviors.indexOf(behavior);
  12813. if (index === -1) {
  12814. return this;
  12815. }
  12816. this._behaviors[index].detach();
  12817. this._behaviors.splice(index, 1);
  12818. return this;
  12819. };
  12820. Object.defineProperty(Node.prototype, "behaviors", {
  12821. get: function () {
  12822. return this._behaviors;
  12823. },
  12824. enumerable: true,
  12825. configurable: true
  12826. });
  12827. Node.prototype.getBehaviorByName = function (name) {
  12828. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  12829. var behavior = _a[_i];
  12830. if (behavior.name === name) {
  12831. return behavior;
  12832. }
  12833. }
  12834. return null;
  12835. };
  12836. // override it in derived class
  12837. Node.prototype.getWorldMatrix = function () {
  12838. return BABYLON.Matrix.Identity();
  12839. };
  12840. // override it in derived class if you add new variables to the cache
  12841. // and call the parent class method
  12842. Node.prototype._initCache = function () {
  12843. this._cache = {};
  12844. this._cache.parent = undefined;
  12845. };
  12846. Node.prototype.updateCache = function (force) {
  12847. if (!force && this.isSynchronized())
  12848. return;
  12849. this._cache.parent = this.parent;
  12850. this._updateCache();
  12851. };
  12852. // override it in derived class if you add new variables to the cache
  12853. // and call the parent class method if !ignoreParentClass
  12854. Node.prototype._updateCache = function (ignoreParentClass) {
  12855. };
  12856. // override it in derived class if you add new variables to the cache
  12857. Node.prototype._isSynchronized = function () {
  12858. return true;
  12859. };
  12860. Node.prototype._markSyncedWithParent = function () {
  12861. if (this.parent) {
  12862. this._parentRenderId = this.parent._currentRenderId;
  12863. }
  12864. };
  12865. Node.prototype.isSynchronizedWithParent = function () {
  12866. if (!this.parent) {
  12867. return true;
  12868. }
  12869. if (this._parentRenderId !== this.parent._currentRenderId) {
  12870. return false;
  12871. }
  12872. return this.parent.isSynchronized();
  12873. };
  12874. Node.prototype.isSynchronized = function (updateCache) {
  12875. var check = this.hasNewParent();
  12876. check = check || !this.isSynchronizedWithParent();
  12877. check = check || !this._isSynchronized();
  12878. if (updateCache)
  12879. this.updateCache(true);
  12880. return !check;
  12881. };
  12882. Node.prototype.hasNewParent = function (update) {
  12883. if (this._cache.parent === this.parent)
  12884. return false;
  12885. if (update)
  12886. this._cache.parent = this.parent;
  12887. return true;
  12888. };
  12889. /**
  12890. * Is this node ready to be used/rendered
  12891. * @return {boolean} is it ready
  12892. */
  12893. Node.prototype.isReady = function () {
  12894. return this._isReady;
  12895. };
  12896. /**
  12897. * Is this node enabled.
  12898. * 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.
  12899. * @param {boolean} [checkAncestors=true] - 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.
  12900. * @return {boolean} whether this node (and its parent) is enabled.
  12901. * @see setEnabled
  12902. */
  12903. Node.prototype.isEnabled = function (checkAncestors) {
  12904. if (checkAncestors === void 0) { checkAncestors = true; }
  12905. if (checkAncestors === false) {
  12906. return this._isEnabled;
  12907. }
  12908. if (this._isEnabled === false) {
  12909. return false;
  12910. }
  12911. if (this.parent !== undefined && this.parent !== null) {
  12912. return this.parent.isEnabled(checkAncestors);
  12913. }
  12914. return true;
  12915. };
  12916. /**
  12917. * Set the enabled state of this node.
  12918. * @param {boolean} value - the new enabled state
  12919. * @see isEnabled
  12920. */
  12921. Node.prototype.setEnabled = function (value) {
  12922. this._isEnabled = value;
  12923. };
  12924. /**
  12925. * Is this node a descendant of the given node.
  12926. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  12927. * @param {BABYLON.Node} ancestor - The parent node to inspect
  12928. * @see parent
  12929. */
  12930. Node.prototype.isDescendantOf = function (ancestor) {
  12931. if (this.parent) {
  12932. if (this.parent === ancestor) {
  12933. return true;
  12934. }
  12935. return this.parent.isDescendantOf(ancestor);
  12936. }
  12937. return false;
  12938. };
  12939. /**
  12940. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  12941. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  12942. * @param {boolean} directDescendantsOnly 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.
  12943. * @param predicate: an optional predicate that will be called on every evaluated children, the predicate must return true for a given child to be part of the result, otherwise it will be ignored.
  12944. */
  12945. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  12946. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  12947. if (!this._children) {
  12948. return;
  12949. }
  12950. for (var index = 0; index < this._children.length; index++) {
  12951. var item = this._children[index];
  12952. if (!predicate || predicate(item)) {
  12953. results.push(item);
  12954. }
  12955. if (!directDescendantsOnly) {
  12956. item._getDescendants(results, false, predicate);
  12957. }
  12958. }
  12959. };
  12960. /**
  12961. * Will return all nodes that have this node as ascendant.
  12962. * @param {boolean} directDescendantsOnly 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.
  12963. * @param predicate: an optional predicate that will be called on every evaluated children, the predicate must return true for a given child to be part of the result, otherwise it will be ignored.
  12964. * @return {BABYLON.Node[]} all children nodes of all types.
  12965. */
  12966. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  12967. var results = new Array();
  12968. this._getDescendants(results, directDescendantsOnly, predicate);
  12969. return results;
  12970. };
  12971. /**
  12972. * Get all child-meshes of this node.
  12973. */
  12974. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  12975. var results = [];
  12976. this._getDescendants(results, directDescendantsOnly, function (node) {
  12977. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  12978. });
  12979. return results;
  12980. };
  12981. /**
  12982. * Get all child-transformNodes of this node.
  12983. */
  12984. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  12985. var results = [];
  12986. this._getDescendants(results, directDescendantsOnly, function (node) {
  12987. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  12988. });
  12989. return results;
  12990. };
  12991. /**
  12992. * Get all direct children of this node.
  12993. */
  12994. Node.prototype.getChildren = function (predicate) {
  12995. return this.getDescendants(true, predicate);
  12996. };
  12997. Node.prototype._setReady = function (state) {
  12998. if (state === this._isReady) {
  12999. return;
  13000. }
  13001. if (!state) {
  13002. this._isReady = false;
  13003. return;
  13004. }
  13005. this._isReady = true;
  13006. if (this.onReady) {
  13007. this.onReady(this);
  13008. }
  13009. };
  13010. Node.prototype.getAnimationByName = function (name) {
  13011. for (var i = 0; i < this.animations.length; i++) {
  13012. var animation = this.animations[i];
  13013. if (animation.name === name) {
  13014. return animation;
  13015. }
  13016. }
  13017. return null;
  13018. };
  13019. Node.prototype.createAnimationRange = function (name, from, to) {
  13020. // check name not already in use
  13021. if (!this._ranges[name]) {
  13022. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  13023. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  13024. if (this.animations[i]) {
  13025. this.animations[i].createRange(name, from, to);
  13026. }
  13027. }
  13028. }
  13029. };
  13030. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  13031. if (deleteFrames === void 0) { deleteFrames = true; }
  13032. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  13033. if (this.animations[i]) {
  13034. this.animations[i].deleteRange(name, deleteFrames);
  13035. }
  13036. }
  13037. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  13038. };
  13039. Node.prototype.getAnimationRange = function (name) {
  13040. return this._ranges[name];
  13041. };
  13042. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  13043. var range = this.getAnimationRange(name);
  13044. if (!range) {
  13045. return;
  13046. }
  13047. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  13048. };
  13049. Node.prototype.serializeAnimationRanges = function () {
  13050. var serializationRanges = [];
  13051. for (var name in this._ranges) {
  13052. var localRange = this._ranges[name];
  13053. if (!localRange) {
  13054. continue;
  13055. }
  13056. var range = {};
  13057. range.name = name;
  13058. range.from = localRange.from;
  13059. range.to = localRange.to;
  13060. serializationRanges.push(range);
  13061. }
  13062. return serializationRanges;
  13063. };
  13064. // override it in derived class
  13065. Node.prototype.computeWorldMatrix = function (force) {
  13066. return BABYLON.Matrix.Identity();
  13067. };
  13068. Node.prototype.dispose = function () {
  13069. this.parent = null;
  13070. // Callback
  13071. this.onDisposeObservable.notifyObservers(this);
  13072. this.onDisposeObservable.clear();
  13073. // Behaviors
  13074. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  13075. var behavior = _a[_i];
  13076. behavior.detach();
  13077. }
  13078. this._behaviors = [];
  13079. };
  13080. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  13081. if (parsedNode.ranges) {
  13082. for (var index = 0; index < parsedNode.ranges.length; index++) {
  13083. var data = parsedNode.ranges[index];
  13084. node.createAnimationRange(data.name, data.from, data.to);
  13085. }
  13086. }
  13087. };
  13088. __decorate([
  13089. BABYLON.serialize()
  13090. ], Node.prototype, "name", void 0);
  13091. __decorate([
  13092. BABYLON.serialize()
  13093. ], Node.prototype, "id", void 0);
  13094. __decorate([
  13095. BABYLON.serialize()
  13096. ], Node.prototype, "uniqueId", void 0);
  13097. __decorate([
  13098. BABYLON.serialize()
  13099. ], Node.prototype, "state", void 0);
  13100. __decorate([
  13101. BABYLON.serialize()
  13102. ], Node.prototype, "metadata", void 0);
  13103. return Node;
  13104. }());
  13105. BABYLON.Node = Node;
  13106. })(BABYLON || (BABYLON = {}));
  13107. //# sourceMappingURL=babylon.node.js.map
  13108. var BABYLON;
  13109. (function (BABYLON) {
  13110. var BoundingSphere = /** @class */ (function () {
  13111. function BoundingSphere(minimum, maximum) {
  13112. this.minimum = minimum;
  13113. this.maximum = maximum;
  13114. this._tempRadiusVector = BABYLON.Vector3.Zero();
  13115. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  13116. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  13117. this.radius = distance * 0.5;
  13118. this.centerWorld = BABYLON.Vector3.Zero();
  13119. this._update(BABYLON.Matrix.Identity());
  13120. }
  13121. // Methods
  13122. BoundingSphere.prototype._update = function (world) {
  13123. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  13124. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  13125. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  13126. };
  13127. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  13128. for (var i = 0; i < 6; i++) {
  13129. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  13130. return false;
  13131. }
  13132. return true;
  13133. };
  13134. BoundingSphere.prototype.intersectsPoint = function (point) {
  13135. var x = this.centerWorld.x - point.x;
  13136. var y = this.centerWorld.y - point.y;
  13137. var z = this.centerWorld.z - point.z;
  13138. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  13139. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  13140. return false;
  13141. return true;
  13142. };
  13143. // Statics
  13144. BoundingSphere.Intersects = function (sphere0, sphere1) {
  13145. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  13146. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  13147. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  13148. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  13149. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  13150. return false;
  13151. return true;
  13152. };
  13153. return BoundingSphere;
  13154. }());
  13155. BABYLON.BoundingSphere = BoundingSphere;
  13156. })(BABYLON || (BABYLON = {}));
  13157. //# sourceMappingURL=babylon.boundingSphere.js.map
  13158. var BABYLON;
  13159. (function (BABYLON) {
  13160. var BoundingBox = /** @class */ (function () {
  13161. function BoundingBox(minimum, maximum) {
  13162. this.minimum = minimum;
  13163. this.maximum = maximum;
  13164. this.vectors = new Array();
  13165. this.vectorsWorld = new Array();
  13166. // Bounding vectors
  13167. this.vectors.push(this.minimum.clone());
  13168. this.vectors.push(this.maximum.clone());
  13169. this.vectors.push(this.minimum.clone());
  13170. this.vectors[2].x = this.maximum.x;
  13171. this.vectors.push(this.minimum.clone());
  13172. this.vectors[3].y = this.maximum.y;
  13173. this.vectors.push(this.minimum.clone());
  13174. this.vectors[4].z = this.maximum.z;
  13175. this.vectors.push(this.maximum.clone());
  13176. this.vectors[5].z = this.minimum.z;
  13177. this.vectors.push(this.maximum.clone());
  13178. this.vectors[6].x = this.minimum.x;
  13179. this.vectors.push(this.maximum.clone());
  13180. this.vectors[7].y = this.minimum.y;
  13181. // OBB
  13182. this.center = this.maximum.add(this.minimum).scale(0.5);
  13183. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  13184. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  13185. // World
  13186. for (var index = 0; index < this.vectors.length; index++) {
  13187. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  13188. }
  13189. this.minimumWorld = BABYLON.Vector3.Zero();
  13190. this.maximumWorld = BABYLON.Vector3.Zero();
  13191. this.centerWorld = BABYLON.Vector3.Zero();
  13192. this.extendSizeWorld = BABYLON.Vector3.Zero();
  13193. this._update(BABYLON.Matrix.Identity());
  13194. }
  13195. // Methods
  13196. BoundingBox.prototype.getWorldMatrix = function () {
  13197. return this._worldMatrix;
  13198. };
  13199. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  13200. this._worldMatrix.copyFrom(matrix);
  13201. return this;
  13202. };
  13203. BoundingBox.prototype._update = function (world) {
  13204. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  13205. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  13206. for (var index = 0; index < this.vectors.length; index++) {
  13207. var v = this.vectorsWorld[index];
  13208. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  13209. if (v.x < this.minimumWorld.x)
  13210. this.minimumWorld.x = v.x;
  13211. if (v.y < this.minimumWorld.y)
  13212. this.minimumWorld.y = v.y;
  13213. if (v.z < this.minimumWorld.z)
  13214. this.minimumWorld.z = v.z;
  13215. if (v.x > this.maximumWorld.x)
  13216. this.maximumWorld.x = v.x;
  13217. if (v.y > this.maximumWorld.y)
  13218. this.maximumWorld.y = v.y;
  13219. if (v.z > this.maximumWorld.z)
  13220. this.maximumWorld.z = v.z;
  13221. }
  13222. // Extend
  13223. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  13224. this.extendSizeWorld.scaleInPlace(0.5);
  13225. // OBB
  13226. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  13227. this.centerWorld.scaleInPlace(0.5);
  13228. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  13229. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  13230. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  13231. this._worldMatrix = world;
  13232. };
  13233. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  13234. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  13235. };
  13236. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  13237. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  13238. };
  13239. BoundingBox.prototype.intersectsPoint = function (point) {
  13240. var delta = -BABYLON.Epsilon;
  13241. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  13242. return false;
  13243. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  13244. return false;
  13245. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  13246. return false;
  13247. return true;
  13248. };
  13249. BoundingBox.prototype.intersectsSphere = function (sphere) {
  13250. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  13251. };
  13252. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  13253. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  13254. return false;
  13255. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  13256. return false;
  13257. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  13258. return false;
  13259. return true;
  13260. };
  13261. // Statics
  13262. BoundingBox.Intersects = function (box0, box1) {
  13263. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  13264. return false;
  13265. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  13266. return false;
  13267. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  13268. return false;
  13269. return true;
  13270. };
  13271. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  13272. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  13273. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  13274. return (num <= (sphereRadius * sphereRadius));
  13275. };
  13276. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  13277. for (var p = 0; p < 6; p++) {
  13278. for (var i = 0; i < 8; i++) {
  13279. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  13280. return false;
  13281. }
  13282. }
  13283. }
  13284. return true;
  13285. };
  13286. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  13287. for (var p = 0; p < 6; p++) {
  13288. var inCount = 8;
  13289. for (var i = 0; i < 8; i++) {
  13290. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  13291. --inCount;
  13292. }
  13293. else {
  13294. break;
  13295. }
  13296. }
  13297. if (inCount === 0)
  13298. return false;
  13299. }
  13300. return true;
  13301. };
  13302. return BoundingBox;
  13303. }());
  13304. BABYLON.BoundingBox = BoundingBox;
  13305. })(BABYLON || (BABYLON = {}));
  13306. //# sourceMappingURL=babylon.boundingBox.js.map
  13307. var BABYLON;
  13308. (function (BABYLON) {
  13309. var computeBoxExtents = function (axis, box) {
  13310. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  13311. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  13312. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  13313. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  13314. var r = r0 + r1 + r2;
  13315. return {
  13316. min: p - r,
  13317. max: p + r
  13318. };
  13319. };
  13320. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  13321. var axisOverlap = function (axis, box0, box1) {
  13322. var result0 = computeBoxExtents(axis, box0);
  13323. var result1 = computeBoxExtents(axis, box1);
  13324. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  13325. };
  13326. var BoundingInfo = /** @class */ (function () {
  13327. function BoundingInfo(minimum, maximum) {
  13328. this.minimum = minimum;
  13329. this.maximum = maximum;
  13330. this._isLocked = false;
  13331. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  13332. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  13333. }
  13334. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  13335. get: function () {
  13336. return this._isLocked;
  13337. },
  13338. set: function (value) {
  13339. this._isLocked = value;
  13340. },
  13341. enumerable: true,
  13342. configurable: true
  13343. });
  13344. // Methods
  13345. BoundingInfo.prototype.update = function (world) {
  13346. if (this._isLocked) {
  13347. return;
  13348. }
  13349. this.boundingBox._update(world);
  13350. this.boundingSphere._update(world);
  13351. };
  13352. /**
  13353. * Recreate the bounding info to be centered around a specific point given a specific extend.
  13354. * @param center New center of the bounding info
  13355. * @param extend New extend of the bounding info
  13356. */
  13357. BoundingInfo.prototype.centerOn = function (center, extend) {
  13358. this.minimum = center.subtract(extend);
  13359. this.maximum = center.add(extend);
  13360. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  13361. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  13362. return this;
  13363. };
  13364. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  13365. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  13366. return false;
  13367. return this.boundingBox.isInFrustum(frustumPlanes);
  13368. };
  13369. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  13370. /**
  13371. * Gets the world distance between the min and max points of the bounding box
  13372. */
  13373. get: function () {
  13374. var boundingBox = this.boundingBox;
  13375. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  13376. return size.length();
  13377. },
  13378. enumerable: true,
  13379. configurable: true
  13380. });
  13381. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  13382. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  13383. };
  13384. BoundingInfo.prototype._checkCollision = function (collider) {
  13385. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  13386. };
  13387. BoundingInfo.prototype.intersectsPoint = function (point) {
  13388. if (!this.boundingSphere.centerWorld) {
  13389. return false;
  13390. }
  13391. if (!this.boundingSphere.intersectsPoint(point)) {
  13392. return false;
  13393. }
  13394. if (!this.boundingBox.intersectsPoint(point)) {
  13395. return false;
  13396. }
  13397. return true;
  13398. };
  13399. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  13400. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  13401. return false;
  13402. }
  13403. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  13404. return false;
  13405. }
  13406. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  13407. return false;
  13408. }
  13409. if (!precise) {
  13410. return true;
  13411. }
  13412. var box0 = this.boundingBox;
  13413. var box1 = boundingInfo.boundingBox;
  13414. if (!axisOverlap(box0.directions[0], box0, box1))
  13415. return false;
  13416. if (!axisOverlap(box0.directions[1], box0, box1))
  13417. return false;
  13418. if (!axisOverlap(box0.directions[2], box0, box1))
  13419. return false;
  13420. if (!axisOverlap(box1.directions[0], box0, box1))
  13421. return false;
  13422. if (!axisOverlap(box1.directions[1], box0, box1))
  13423. return false;
  13424. if (!axisOverlap(box1.directions[2], box0, box1))
  13425. return false;
  13426. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  13427. return false;
  13428. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  13429. return false;
  13430. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  13431. return false;
  13432. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  13433. return false;
  13434. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  13435. return false;
  13436. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  13437. return false;
  13438. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  13439. return false;
  13440. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  13441. return false;
  13442. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  13443. return false;
  13444. return true;
  13445. };
  13446. return BoundingInfo;
  13447. }());
  13448. BABYLON.BoundingInfo = BoundingInfo;
  13449. })(BABYLON || (BABYLON = {}));
  13450. //# sourceMappingURL=babylon.boundingInfo.js.map
  13451. var BABYLON;
  13452. (function (BABYLON) {
  13453. var TransformNode = /** @class */ (function (_super) {
  13454. __extends(TransformNode, _super);
  13455. function TransformNode(name, scene, isPure) {
  13456. if (scene === void 0) { scene = null; }
  13457. if (isPure === void 0) { isPure = true; }
  13458. var _this = _super.call(this, name, scene) || this;
  13459. // Properties
  13460. _this._rotation = BABYLON.Vector3.Zero();
  13461. _this._scaling = BABYLON.Vector3.One();
  13462. _this._isDirty = false;
  13463. _this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_NONE;
  13464. _this.scalingDeterminant = 1;
  13465. _this.infiniteDistance = false;
  13466. _this.position = BABYLON.Vector3.Zero();
  13467. _this._localWorld = BABYLON.Matrix.Zero();
  13468. _this._worldMatrix = BABYLON.Matrix.Zero();
  13469. _this._worldMatrixDeterminant = 0;
  13470. _this._absolutePosition = BABYLON.Vector3.Zero();
  13471. _this._pivotMatrix = BABYLON.Matrix.Identity();
  13472. _this._postMultiplyPivotMatrix = false;
  13473. _this._isWorldMatrixFrozen = false;
  13474. /**
  13475. * An event triggered after the world matrix is updated
  13476. * @type {BABYLON.Observable}
  13477. */
  13478. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  13479. _this._nonUniformScaling = false;
  13480. if (isPure) {
  13481. _this.getScene().addTransformNode(_this);
  13482. }
  13483. return _this;
  13484. }
  13485. Object.defineProperty(TransformNode.prototype, "rotation", {
  13486. /**
  13487. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  13488. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  13489. * Default : (0.0, 0.0, 0.0)
  13490. */
  13491. get: function () {
  13492. return this._rotation;
  13493. },
  13494. set: function (newRotation) {
  13495. this._rotation = newRotation;
  13496. },
  13497. enumerable: true,
  13498. configurable: true
  13499. });
  13500. Object.defineProperty(TransformNode.prototype, "scaling", {
  13501. /**
  13502. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  13503. * Default : (1.0, 1.0, 1.0)
  13504. */
  13505. get: function () {
  13506. return this._scaling;
  13507. },
  13508. /**
  13509. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  13510. * Default : (1.0, 1.0, 1.0)
  13511. */
  13512. set: function (newScaling) {
  13513. this._scaling = newScaling;
  13514. },
  13515. enumerable: true,
  13516. configurable: true
  13517. });
  13518. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  13519. /**
  13520. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  13521. * It's null by default.
  13522. * 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)
  13523. */
  13524. get: function () {
  13525. return this._rotationQuaternion;
  13526. },
  13527. set: function (quaternion) {
  13528. this._rotationQuaternion = quaternion;
  13529. //reset the rotation vector.
  13530. if (quaternion && this.rotation.length()) {
  13531. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  13532. }
  13533. },
  13534. enumerable: true,
  13535. configurable: true
  13536. });
  13537. /**
  13538. * Returns the latest update of the World matrix
  13539. * Returns a Matrix.
  13540. */
  13541. TransformNode.prototype.getWorldMatrix = function () {
  13542. if (this._currentRenderId !== this.getScene().getRenderId()) {
  13543. this.computeWorldMatrix();
  13544. }
  13545. return this._worldMatrix;
  13546. };
  13547. /**
  13548. * Returns the latest update of the World matrix determinant.
  13549. */
  13550. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  13551. if (this._currentRenderId !== this.getScene().getRenderId()) {
  13552. this.computeWorldMatrix();
  13553. }
  13554. return this._worldMatrixDeterminant;
  13555. };
  13556. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  13557. /**
  13558. * Returns directly the latest state of the mesh World matrix.
  13559. * A Matrix is returned.
  13560. */
  13561. get: function () {
  13562. return this._worldMatrix;
  13563. },
  13564. enumerable: true,
  13565. configurable: true
  13566. });
  13567. /**
  13568. * Copies the paramater passed Matrix into the mesh Pose matrix.
  13569. * Returns the AbstractMesh.
  13570. */
  13571. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  13572. this._poseMatrix.copyFrom(matrix);
  13573. return this;
  13574. };
  13575. /**
  13576. * Returns the mesh Pose matrix.
  13577. * Returned object : Matrix
  13578. */
  13579. TransformNode.prototype.getPoseMatrix = function () {
  13580. return this._poseMatrix;
  13581. };
  13582. TransformNode.prototype._isSynchronized = function () {
  13583. if (this._isDirty) {
  13584. return false;
  13585. }
  13586. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE)
  13587. return false;
  13588. if (this._cache.pivotMatrixUpdated) {
  13589. return false;
  13590. }
  13591. if (this.infiniteDistance) {
  13592. return false;
  13593. }
  13594. if (!this._cache.position.equals(this.position))
  13595. return false;
  13596. if (this.rotationQuaternion) {
  13597. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  13598. return false;
  13599. }
  13600. if (!this._cache.rotation.equals(this.rotation))
  13601. return false;
  13602. if (!this._cache.scaling.equals(this.scaling))
  13603. return false;
  13604. return true;
  13605. };
  13606. TransformNode.prototype._initCache = function () {
  13607. _super.prototype._initCache.call(this);
  13608. this._cache.localMatrixUpdated = false;
  13609. this._cache.position = BABYLON.Vector3.Zero();
  13610. this._cache.scaling = BABYLON.Vector3.Zero();
  13611. this._cache.rotation = BABYLON.Vector3.Zero();
  13612. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  13613. this._cache.billboardMode = -1;
  13614. };
  13615. TransformNode.prototype.markAsDirty = function (property) {
  13616. if (property === "rotation") {
  13617. this.rotationQuaternion = null;
  13618. }
  13619. this._currentRenderId = Number.MAX_VALUE;
  13620. this._isDirty = true;
  13621. return this;
  13622. };
  13623. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  13624. /**
  13625. * Returns the current mesh absolute position.
  13626. * Retuns a Vector3.
  13627. */
  13628. get: function () {
  13629. return this._absolutePosition;
  13630. },
  13631. enumerable: true,
  13632. configurable: true
  13633. });
  13634. /**
  13635. * Sets a new pivot matrix to the mesh.
  13636. * Returns the AbstractMesh.
  13637. */
  13638. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  13639. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = false; }
  13640. this._pivotMatrix = matrix.clone();
  13641. this._cache.pivotMatrixUpdated = true;
  13642. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  13643. if (this._postMultiplyPivotMatrix) {
  13644. this._pivotMatrixInverse = BABYLON.Matrix.Invert(matrix);
  13645. }
  13646. return this;
  13647. };
  13648. /**
  13649. * Returns the mesh pivot matrix.
  13650. * Default : Identity.
  13651. * A Matrix is returned.
  13652. */
  13653. TransformNode.prototype.getPivotMatrix = function () {
  13654. return this._pivotMatrix;
  13655. };
  13656. /**
  13657. * Prevents the World matrix to be computed any longer.
  13658. * Returns the AbstractMesh.
  13659. */
  13660. TransformNode.prototype.freezeWorldMatrix = function () {
  13661. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  13662. this.computeWorldMatrix(true);
  13663. this._isWorldMatrixFrozen = true;
  13664. return this;
  13665. };
  13666. /**
  13667. * Allows back the World matrix computation.
  13668. * Returns the AbstractMesh.
  13669. */
  13670. TransformNode.prototype.unfreezeWorldMatrix = function () {
  13671. this._isWorldMatrixFrozen = false;
  13672. this.computeWorldMatrix(true);
  13673. return this;
  13674. };
  13675. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  13676. /**
  13677. * True if the World matrix has been frozen.
  13678. * Returns a boolean.
  13679. */
  13680. get: function () {
  13681. return this._isWorldMatrixFrozen;
  13682. },
  13683. enumerable: true,
  13684. configurable: true
  13685. });
  13686. /**
  13687. * Retuns the mesh absolute position in the World.
  13688. * Returns a Vector3.
  13689. */
  13690. TransformNode.prototype.getAbsolutePosition = function () {
  13691. this.computeWorldMatrix();
  13692. return this._absolutePosition;
  13693. };
  13694. /**
  13695. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  13696. * Returns the AbstractMesh.
  13697. */
  13698. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  13699. if (!absolutePosition) {
  13700. return this;
  13701. }
  13702. var absolutePositionX;
  13703. var absolutePositionY;
  13704. var absolutePositionZ;
  13705. if (absolutePosition.x === undefined) {
  13706. if (arguments.length < 3) {
  13707. return this;
  13708. }
  13709. absolutePositionX = arguments[0];
  13710. absolutePositionY = arguments[1];
  13711. absolutePositionZ = arguments[2];
  13712. }
  13713. else {
  13714. absolutePositionX = absolutePosition.x;
  13715. absolutePositionY = absolutePosition.y;
  13716. absolutePositionZ = absolutePosition.z;
  13717. }
  13718. if (this.parent) {
  13719. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  13720. invertParentWorldMatrix.invert();
  13721. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  13722. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  13723. }
  13724. else {
  13725. this.position.x = absolutePositionX;
  13726. this.position.y = absolutePositionY;
  13727. this.position.z = absolutePositionZ;
  13728. }
  13729. return this;
  13730. };
  13731. /**
  13732. * Sets the mesh position in its local space.
  13733. * Returns the AbstractMesh.
  13734. */
  13735. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  13736. this.computeWorldMatrix();
  13737. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  13738. return this;
  13739. };
  13740. /**
  13741. * Returns the mesh position in the local space from the current World matrix values.
  13742. * Returns a new Vector3.
  13743. */
  13744. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  13745. this.computeWorldMatrix();
  13746. var invLocalWorldMatrix = this._localWorld.clone();
  13747. invLocalWorldMatrix.invert();
  13748. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  13749. };
  13750. /**
  13751. * Translates the mesh along the passed Vector3 in its local space.
  13752. * Returns the AbstractMesh.
  13753. */
  13754. TransformNode.prototype.locallyTranslate = function (vector3) {
  13755. this.computeWorldMatrix(true);
  13756. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  13757. return this;
  13758. };
  13759. /**
  13760. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  13761. * @param targetPoint the position (must be in same space as current mesh) to look at
  13762. * @param yawCor optional yaw (y-axis) correction in radians
  13763. * @param pitchCor optional pitch (x-axis) correction in radians
  13764. * @param rollCor optional roll (z-axis) correction in radians
  13765. * @param space the choosen space of the target
  13766. * @returns the TransformNode.
  13767. */
  13768. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  13769. if (yawCor === void 0) { yawCor = 0; }
  13770. if (pitchCor === void 0) { pitchCor = 0; }
  13771. if (rollCor === void 0) { rollCor = 0; }
  13772. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  13773. var dv = BABYLON.AbstractMesh._lookAtVectorCache;
  13774. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  13775. targetPoint.subtractToRef(pos, dv);
  13776. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  13777. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  13778. var pitch = Math.atan2(dv.y, len);
  13779. if (this.rotationQuaternion) {
  13780. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  13781. }
  13782. else {
  13783. this.rotation.x = pitch + pitchCor;
  13784. this.rotation.y = yaw + yawCor;
  13785. this.rotation.z = rollCor;
  13786. }
  13787. return this;
  13788. };
  13789. /**
  13790. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  13791. * This Vector3 is expressed in the World space.
  13792. */
  13793. TransformNode.prototype.getDirection = function (localAxis) {
  13794. var result = BABYLON.Vector3.Zero();
  13795. this.getDirectionToRef(localAxis, result);
  13796. return result;
  13797. };
  13798. /**
  13799. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  13800. * localAxis is expressed in the mesh local space.
  13801. * result is computed in the Wordl space from the mesh World matrix.
  13802. * Returns the AbstractMesh.
  13803. */
  13804. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  13805. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  13806. return this;
  13807. };
  13808. TransformNode.prototype.setPivotPoint = function (point, space) {
  13809. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  13810. if (this.getScene().getRenderId() == 0) {
  13811. this.computeWorldMatrix(true);
  13812. }
  13813. var wm = this.getWorldMatrix();
  13814. if (space == BABYLON.Space.WORLD) {
  13815. var tmat = BABYLON.Tmp.Matrix[0];
  13816. wm.invertToRef(tmat);
  13817. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  13818. }
  13819. BABYLON.Vector3.TransformCoordinatesToRef(point, wm, this.position);
  13820. this._pivotMatrix.m[12] = -point.x;
  13821. this._pivotMatrix.m[13] = -point.y;
  13822. this._pivotMatrix.m[14] = -point.z;
  13823. this._cache.pivotMatrixUpdated = true;
  13824. return this;
  13825. };
  13826. /**
  13827. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  13828. */
  13829. TransformNode.prototype.getPivotPoint = function () {
  13830. var point = BABYLON.Vector3.Zero();
  13831. this.getPivotPointToRef(point);
  13832. return point;
  13833. };
  13834. /**
  13835. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  13836. * Returns the AbstractMesh.
  13837. */
  13838. TransformNode.prototype.getPivotPointToRef = function (result) {
  13839. result.x = -this._pivotMatrix.m[12];
  13840. result.y = -this._pivotMatrix.m[13];
  13841. result.z = -this._pivotMatrix.m[14];
  13842. return this;
  13843. };
  13844. /**
  13845. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  13846. */
  13847. TransformNode.prototype.getAbsolutePivotPoint = function () {
  13848. var point = BABYLON.Vector3.Zero();
  13849. this.getAbsolutePivotPointToRef(point);
  13850. return point;
  13851. };
  13852. /**
  13853. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  13854. * Returns the AbstractMesh.
  13855. */
  13856. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  13857. result.x = this._pivotMatrix.m[12];
  13858. result.y = this._pivotMatrix.m[13];
  13859. result.z = this._pivotMatrix.m[14];
  13860. this.getPivotPointToRef(result);
  13861. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  13862. return this;
  13863. };
  13864. /**
  13865. * Defines the passed node as the parent of the current node.
  13866. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  13867. * Returns the TransformNode.
  13868. */
  13869. TransformNode.prototype.setParent = function (node) {
  13870. if (node === null) {
  13871. var rotation = BABYLON.Tmp.Quaternion[0];
  13872. var position = BABYLON.Tmp.Vector3[0];
  13873. var scale = BABYLON.Tmp.Vector3[1];
  13874. if (this.parent && this.parent.computeWorldMatrix) {
  13875. this.parent.computeWorldMatrix(true);
  13876. }
  13877. this.computeWorldMatrix(true);
  13878. this.getWorldMatrix().decompose(scale, rotation, position);
  13879. if (this.rotationQuaternion) {
  13880. this.rotationQuaternion.copyFrom(rotation);
  13881. }
  13882. else {
  13883. rotation.toEulerAnglesToRef(this.rotation);
  13884. }
  13885. this.scaling.x = scale.x;
  13886. this.scaling.y = scale.y;
  13887. this.scaling.z = scale.z;
  13888. this.position.x = position.x;
  13889. this.position.y = position.y;
  13890. this.position.z = position.z;
  13891. }
  13892. else {
  13893. var rotation = BABYLON.Tmp.Quaternion[0];
  13894. var position = BABYLON.Tmp.Vector3[0];
  13895. var scale = BABYLON.Tmp.Vector3[1];
  13896. var diffMatrix = BABYLON.Tmp.Matrix[0];
  13897. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  13898. this.computeWorldMatrix(true);
  13899. node.computeWorldMatrix(true);
  13900. node.getWorldMatrix().invertToRef(invParentMatrix);
  13901. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  13902. diffMatrix.decompose(scale, rotation, position);
  13903. if (this.rotationQuaternion) {
  13904. this.rotationQuaternion.copyFrom(rotation);
  13905. }
  13906. else {
  13907. rotation.toEulerAnglesToRef(this.rotation);
  13908. }
  13909. this.position.x = position.x;
  13910. this.position.y = position.y;
  13911. this.position.z = position.z;
  13912. this.scaling.x = scale.x;
  13913. this.scaling.y = scale.y;
  13914. this.scaling.z = scale.z;
  13915. }
  13916. this.parent = node;
  13917. return this;
  13918. };
  13919. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  13920. get: function () {
  13921. return this._nonUniformScaling;
  13922. },
  13923. enumerable: true,
  13924. configurable: true
  13925. });
  13926. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  13927. if (this._nonUniformScaling === value) {
  13928. return false;
  13929. }
  13930. this._nonUniformScaling = true;
  13931. return true;
  13932. };
  13933. /**
  13934. * Attach the current TransformNode to another TransformNode associated with a bone
  13935. * @param bone Bone affecting the TransformNode
  13936. * @param affectedTransformNode TransformNode associated with the bone
  13937. */
  13938. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  13939. this._transformToBoneReferal = affectedTransformNode;
  13940. this.parent = bone;
  13941. if (bone.getWorldMatrix().determinant() < 0) {
  13942. this.scalingDeterminant *= -1;
  13943. }
  13944. return this;
  13945. };
  13946. TransformNode.prototype.detachFromBone = function () {
  13947. if (!this.parent) {
  13948. return this;
  13949. }
  13950. if (this.parent.getWorldMatrix().determinant() < 0) {
  13951. this.scalingDeterminant *= -1;
  13952. }
  13953. this._transformToBoneReferal = null;
  13954. this.parent = null;
  13955. return this;
  13956. };
  13957. /**
  13958. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  13959. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  13960. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  13961. * The passed axis is also normalized.
  13962. * Returns the AbstractMesh.
  13963. */
  13964. TransformNode.prototype.rotate = function (axis, amount, space) {
  13965. axis.normalize();
  13966. if (!this.rotationQuaternion) {
  13967. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  13968. this.rotation = BABYLON.Vector3.Zero();
  13969. }
  13970. var rotationQuaternion;
  13971. if (!space || space === BABYLON.Space.LOCAL) {
  13972. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  13973. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  13974. }
  13975. else {
  13976. if (this.parent) {
  13977. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  13978. invertParentWorldMatrix.invert();
  13979. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  13980. }
  13981. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  13982. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  13983. }
  13984. return this;
  13985. };
  13986. /**
  13987. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  13988. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  13989. * The passed axis is also normalized.
  13990. * Returns the AbstractMesh.
  13991. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  13992. */
  13993. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  13994. axis.normalize();
  13995. if (!this.rotationQuaternion) {
  13996. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  13997. this.rotation.copyFromFloats(0, 0, 0);
  13998. }
  13999. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  14000. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  14001. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  14002. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  14003. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  14004. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  14005. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  14006. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  14007. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  14008. return this;
  14009. };
  14010. /**
  14011. * Translates the mesh along the axis vector for the passed distance in the given space.
  14012. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  14013. * Returns the AbstractMesh.
  14014. */
  14015. TransformNode.prototype.translate = function (axis, distance, space) {
  14016. var displacementVector = axis.scale(distance);
  14017. if (!space || space === BABYLON.Space.LOCAL) {
  14018. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  14019. this.setPositionWithLocalVector(tempV3);
  14020. }
  14021. else {
  14022. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  14023. }
  14024. return this;
  14025. };
  14026. /**
  14027. * Adds a rotation step to the mesh current rotation.
  14028. * x, y, z are Euler angles expressed in radians.
  14029. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  14030. * This means this rotation is made in the mesh local space only.
  14031. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  14032. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  14033. * ```javascript
  14034. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  14035. * ```
  14036. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  14037. * 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.
  14038. * Returns the AbstractMesh.
  14039. */
  14040. TransformNode.prototype.addRotation = function (x, y, z) {
  14041. var rotationQuaternion;
  14042. if (this.rotationQuaternion) {
  14043. rotationQuaternion = this.rotationQuaternion;
  14044. }
  14045. else {
  14046. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  14047. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  14048. }
  14049. var accumulation = BABYLON.Tmp.Quaternion[0];
  14050. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  14051. rotationQuaternion.multiplyInPlace(accumulation);
  14052. if (!this.rotationQuaternion) {
  14053. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  14054. }
  14055. return this;
  14056. };
  14057. /**
  14058. * Computes the mesh World matrix and returns it.
  14059. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  14060. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  14061. * If the parameter `force`is set to `true`, the actual computation is done.
  14062. * Returns the mesh World Matrix.
  14063. */
  14064. TransformNode.prototype.computeWorldMatrix = function (force) {
  14065. if (this._isWorldMatrixFrozen) {
  14066. return this._worldMatrix;
  14067. }
  14068. if (!force && this.isSynchronized(true)) {
  14069. return this._worldMatrix;
  14070. }
  14071. this._cache.position.copyFrom(this.position);
  14072. this._cache.scaling.copyFrom(this.scaling);
  14073. this._cache.pivotMatrixUpdated = false;
  14074. this._cache.billboardMode = this.billboardMode;
  14075. this._currentRenderId = this.getScene().getRenderId();
  14076. this._isDirty = false;
  14077. // Scaling
  14078. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  14079. // Rotation
  14080. //rotate, if quaternion is set and rotation was used
  14081. if (this.rotationQuaternion) {
  14082. var len = this.rotation.length();
  14083. if (len) {
  14084. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  14085. this.rotation.copyFromFloats(0, 0, 0);
  14086. }
  14087. }
  14088. if (this.rotationQuaternion) {
  14089. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  14090. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  14091. }
  14092. else {
  14093. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  14094. this._cache.rotation.copyFrom(this.rotation);
  14095. }
  14096. // Translation
  14097. var camera = this.getScene().activeCamera;
  14098. if (this.infiniteDistance && !this.parent && camera) {
  14099. var cameraWorldMatrix = camera.getWorldMatrix();
  14100. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  14101. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  14102. }
  14103. else {
  14104. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  14105. }
  14106. // Composing transformations
  14107. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  14108. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  14109. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  14110. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE && camera) {
  14111. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_ALL) !== BABYLON.AbstractMesh.BILLBOARDMODE_ALL) {
  14112. // Need to decompose each rotation here
  14113. var currentPosition = BABYLON.Tmp.Vector3[3];
  14114. if (this.parent && this.parent.getWorldMatrix) {
  14115. if (this._transformToBoneReferal) {
  14116. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  14117. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  14118. }
  14119. else {
  14120. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  14121. }
  14122. }
  14123. else {
  14124. currentPosition.copyFrom(this.position);
  14125. }
  14126. currentPosition.subtractInPlace(camera.globalPosition);
  14127. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  14128. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X) === BABYLON.AbstractMesh.BILLBOARDMODE_X) {
  14129. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  14130. }
  14131. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y) === BABYLON.AbstractMesh.BILLBOARDMODE_Y) {
  14132. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  14133. }
  14134. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z) === BABYLON.AbstractMesh.BILLBOARDMODE_Z) {
  14135. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  14136. }
  14137. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  14138. }
  14139. else {
  14140. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  14141. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  14142. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  14143. }
  14144. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  14145. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  14146. }
  14147. // Local world
  14148. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  14149. // Parent
  14150. if (this.parent && this.parent.getWorldMatrix) {
  14151. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  14152. if (this._transformToBoneReferal) {
  14153. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  14154. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  14155. }
  14156. else {
  14157. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  14158. }
  14159. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  14160. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  14161. this._worldMatrix.copyFrom(this._localWorld);
  14162. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  14163. }
  14164. else {
  14165. if (this._transformToBoneReferal) {
  14166. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  14167. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  14168. }
  14169. else {
  14170. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  14171. }
  14172. }
  14173. this._markSyncedWithParent();
  14174. }
  14175. else {
  14176. this._worldMatrix.copyFrom(this._localWorld);
  14177. }
  14178. // Post multiply inverse of pivotMatrix
  14179. if (this._postMultiplyPivotMatrix) {
  14180. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  14181. }
  14182. // Normal matrix
  14183. if (this.scaling.isNonUniform) {
  14184. this._updateNonUniformScalingState(true);
  14185. }
  14186. else if (this.parent && this.parent._nonUniformScaling) {
  14187. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  14188. }
  14189. else {
  14190. this._updateNonUniformScalingState(false);
  14191. }
  14192. this._afterComputeWorldMatrix();
  14193. // Absolute position
  14194. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  14195. // Callbacks
  14196. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  14197. if (!this._poseMatrix) {
  14198. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  14199. }
  14200. // Cache the determinant
  14201. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  14202. return this._worldMatrix;
  14203. };
  14204. TransformNode.prototype._afterComputeWorldMatrix = function () {
  14205. };
  14206. /**
  14207. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  14208. * @param func: callback function to add
  14209. *
  14210. * Returns the TransformNode.
  14211. */
  14212. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  14213. this.onAfterWorldMatrixUpdateObservable.add(func);
  14214. return this;
  14215. };
  14216. /**
  14217. * Removes a registered callback function.
  14218. * Returns the TransformNode.
  14219. */
  14220. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  14221. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  14222. return this;
  14223. };
  14224. /**
  14225. * Clone the current transform node
  14226. * Returns the new transform node
  14227. * @param name Name of the new clone
  14228. * @param newParent New parent for the clone
  14229. * @param doNotCloneChildren Do not clone children hierarchy
  14230. */
  14231. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  14232. var _this = this;
  14233. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  14234. result.name = name;
  14235. result.id = name;
  14236. if (newParent) {
  14237. result.parent = newParent;
  14238. }
  14239. if (!doNotCloneChildren) {
  14240. // Children
  14241. var directDescendants = this.getDescendants(true);
  14242. for (var index = 0; index < directDescendants.length; index++) {
  14243. var child = directDescendants[index];
  14244. if (child.clone) {
  14245. child.clone(name + "." + child.name, result);
  14246. }
  14247. }
  14248. }
  14249. return result;
  14250. };
  14251. TransformNode.prototype.serialize = function (currentSerializationObject) {
  14252. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  14253. serializationObject.type = this.getClassName();
  14254. // Parent
  14255. if (this.parent) {
  14256. serializationObject.parentId = this.parent.id;
  14257. }
  14258. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  14259. serializationObject.tags = BABYLON.Tags.GetTags(this);
  14260. }
  14261. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  14262. serializationObject.isEnabled = this.isEnabled();
  14263. // Parent
  14264. if (this.parent) {
  14265. serializationObject.parentId = this.parent.id;
  14266. }
  14267. return serializationObject;
  14268. };
  14269. // Statics
  14270. /**
  14271. * Returns a new TransformNode object parsed from the source provided.
  14272. * The parameter `parsedMesh` is the source.
  14273. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  14274. */
  14275. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  14276. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  14277. if (BABYLON.Tags) {
  14278. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  14279. }
  14280. if (parsedTransformNode.localMatrix) {
  14281. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  14282. }
  14283. else if (parsedTransformNode.pivotMatrix) {
  14284. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  14285. }
  14286. transformNode.setEnabled(parsedTransformNode.isEnabled);
  14287. // Parent
  14288. if (parsedTransformNode.parentId) {
  14289. transformNode._waitingParentId = parsedTransformNode.parentId;
  14290. }
  14291. return transformNode;
  14292. };
  14293. /**
  14294. * Disposes the TransformNode.
  14295. * By default, all the children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  14296. * Returns nothing.
  14297. */
  14298. TransformNode.prototype.dispose = function (doNotRecurse) {
  14299. // Animations
  14300. this.getScene().stopAnimation(this);
  14301. // Remove from scene
  14302. this.getScene().removeTransformNode(this);
  14303. this._cache = {};
  14304. if (!doNotRecurse) {
  14305. // Children
  14306. var objects = this.getDescendants(true);
  14307. for (var index = 0; index < objects.length; index++) {
  14308. objects[index].dispose();
  14309. }
  14310. }
  14311. else {
  14312. var childMeshes = this.getChildMeshes(true);
  14313. for (index = 0; index < childMeshes.length; index++) {
  14314. var child = childMeshes[index];
  14315. child.parent = null;
  14316. child.computeWorldMatrix(true);
  14317. }
  14318. }
  14319. this.onAfterWorldMatrixUpdateObservable.clear();
  14320. _super.prototype.dispose.call(this);
  14321. };
  14322. // Statics
  14323. TransformNode.BILLBOARDMODE_NONE = 0;
  14324. TransformNode.BILLBOARDMODE_X = 1;
  14325. TransformNode.BILLBOARDMODE_Y = 2;
  14326. TransformNode.BILLBOARDMODE_Z = 4;
  14327. TransformNode.BILLBOARDMODE_ALL = 7;
  14328. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  14329. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  14330. __decorate([
  14331. BABYLON.serializeAsVector3()
  14332. ], TransformNode.prototype, "_rotation", void 0);
  14333. __decorate([
  14334. BABYLON.serializeAsQuaternion()
  14335. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  14336. __decorate([
  14337. BABYLON.serializeAsVector3()
  14338. ], TransformNode.prototype, "_scaling", void 0);
  14339. __decorate([
  14340. BABYLON.serialize()
  14341. ], TransformNode.prototype, "billboardMode", void 0);
  14342. __decorate([
  14343. BABYLON.serialize()
  14344. ], TransformNode.prototype, "scalingDeterminant", void 0);
  14345. __decorate([
  14346. BABYLON.serialize()
  14347. ], TransformNode.prototype, "infiniteDistance", void 0);
  14348. __decorate([
  14349. BABYLON.serializeAsVector3()
  14350. ], TransformNode.prototype, "position", void 0);
  14351. return TransformNode;
  14352. }(BABYLON.Node));
  14353. BABYLON.TransformNode = TransformNode;
  14354. })(BABYLON || (BABYLON = {}));
  14355. //# sourceMappingURL=babylon.transformNode.js.map
  14356. var BABYLON;
  14357. (function (BABYLON) {
  14358. var AbstractMesh = /** @class */ (function (_super) {
  14359. __extends(AbstractMesh, _super);
  14360. // Constructor
  14361. function AbstractMesh(name, scene) {
  14362. if (scene === void 0) { scene = null; }
  14363. var _this = _super.call(this, name, scene, false) || this;
  14364. _this._facetNb = 0; // facet number
  14365. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  14366. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  14367. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  14368. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  14369. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  14370. _this._subDiv = {
  14371. max: 1,
  14372. X: 1,
  14373. Y: 1,
  14374. Z: 1
  14375. };
  14376. _this._facetDepthSort = false; // is the facet depth sort to be computed
  14377. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  14378. // Events
  14379. /**
  14380. * An event triggered when this mesh collides with another one
  14381. * @type {BABYLON.Observable}
  14382. */
  14383. _this.onCollideObservable = new BABYLON.Observable();
  14384. /**
  14385. * An event triggered when the collision's position changes
  14386. * @type {BABYLON.Observable}
  14387. */
  14388. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  14389. /**
  14390. * An event triggered when material is changed
  14391. * @type {BABYLON.Observable}
  14392. */
  14393. _this.onMaterialChangedObservable = new BABYLON.Observable();
  14394. // Properties
  14395. _this.definedFacingForward = true; // orientation for POV movement & rotation
  14396. /**
  14397. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  14398. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  14399. * or
  14400. * 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.
  14401. * for more info check WebGl documentations
  14402. */
  14403. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  14404. /**
  14405. * 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:
  14406. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  14407. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  14408. * 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.
  14409. */
  14410. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  14411. /**
  14412. * 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.
  14413. * The default value is -1 which means don't break the query and wait till the result.
  14414. */
  14415. _this.occlusionRetryCount = -1;
  14416. _this._occlusionInternalRetryCounter = 0;
  14417. _this._isOccluded = false;
  14418. _this._isOcclusionQueryInProgress = false;
  14419. _this.visibility = 1.0;
  14420. _this.alphaIndex = Number.MAX_VALUE;
  14421. _this.isVisible = true;
  14422. _this.isPickable = true;
  14423. _this.showBoundingBox = false;
  14424. _this.showSubMeshesBoundingBox = false;
  14425. _this.isBlocker = false;
  14426. _this.enablePointerMoveEvents = false;
  14427. _this.renderingGroupId = 0;
  14428. _this._receiveShadows = false;
  14429. _this.renderOutline = false;
  14430. _this.outlineColor = BABYLON.Color3.Red();
  14431. _this.outlineWidth = 0.02;
  14432. _this.renderOverlay = false;
  14433. _this.overlayColor = BABYLON.Color3.Red();
  14434. _this.overlayAlpha = 0.5;
  14435. _this._hasVertexAlpha = false;
  14436. _this._useVertexColors = true;
  14437. _this._computeBonesUsingShaders = true;
  14438. _this._numBoneInfluencers = 4;
  14439. _this._applyFog = true;
  14440. _this.useOctreeForRenderingSelection = true;
  14441. _this.useOctreeForPicking = true;
  14442. _this.useOctreeForCollisions = true;
  14443. _this._layerMask = 0x0FFFFFFF;
  14444. /**
  14445. * True if the mesh must be rendered in any case.
  14446. */
  14447. _this.alwaysSelectAsActiveMesh = false;
  14448. /**
  14449. * This scene's action manager
  14450. * @type {BABYLON.ActionManager}
  14451. */
  14452. _this.actionManager = null;
  14453. // Physics
  14454. _this.physicsImpostor = null;
  14455. // Collisions
  14456. _this._checkCollisions = false;
  14457. _this._collisionMask = -1;
  14458. _this._collisionGroup = -1;
  14459. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  14460. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  14461. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  14462. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  14463. // Edges
  14464. _this.edgesWidth = 1;
  14465. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  14466. // Cache
  14467. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  14468. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  14469. _this._isDisposed = false;
  14470. _this._renderId = 0;
  14471. _this._intersectionsInProgress = new Array();
  14472. _this._unIndexed = false;
  14473. _this._lightSources = new Array();
  14474. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  14475. if (collidedMesh === void 0) { collidedMesh = null; }
  14476. //TODO move this to the collision coordinator!
  14477. if (_this.getScene().workerCollisions)
  14478. newPosition.multiplyInPlace(_this._collider._radius);
  14479. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  14480. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  14481. _this.position.addInPlace(_this._diffPositionForCollisions);
  14482. }
  14483. if (collidedMesh) {
  14484. _this.onCollideObservable.notifyObservers(collidedMesh);
  14485. }
  14486. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  14487. };
  14488. _this.getScene().addMesh(_this);
  14489. _this._resyncLightSources();
  14490. return _this;
  14491. }
  14492. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  14493. get: function () {
  14494. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  14495. },
  14496. enumerable: true,
  14497. configurable: true
  14498. });
  14499. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  14500. get: function () {
  14501. return BABYLON.TransformNode.BILLBOARDMODE_X;
  14502. },
  14503. enumerable: true,
  14504. configurable: true
  14505. });
  14506. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  14507. get: function () {
  14508. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  14509. },
  14510. enumerable: true,
  14511. configurable: true
  14512. });
  14513. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  14514. get: function () {
  14515. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  14516. },
  14517. enumerable: true,
  14518. configurable: true
  14519. });
  14520. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  14521. get: function () {
  14522. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  14523. },
  14524. enumerable: true,
  14525. configurable: true
  14526. });
  14527. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  14528. /**
  14529. * Read-only : the number of facets in the mesh
  14530. */
  14531. get: function () {
  14532. return this._facetNb;
  14533. },
  14534. enumerable: true,
  14535. configurable: true
  14536. });
  14537. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  14538. /**
  14539. * The number (integer) of subdivisions per axis in the partioning space
  14540. */
  14541. get: function () {
  14542. return this._partitioningSubdivisions;
  14543. },
  14544. set: function (nb) {
  14545. this._partitioningSubdivisions = nb;
  14546. },
  14547. enumerable: true,
  14548. configurable: true
  14549. });
  14550. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  14551. /**
  14552. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  14553. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  14554. */
  14555. get: function () {
  14556. return this._partitioningBBoxRatio;
  14557. },
  14558. set: function (ratio) {
  14559. this._partitioningBBoxRatio = ratio;
  14560. },
  14561. enumerable: true,
  14562. configurable: true
  14563. });
  14564. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  14565. /**
  14566. * Boolean : must the facet be depth sorted on next call to `updateFacetData()` ?
  14567. * Works only for updatable meshes.
  14568. * Doesn't work with multi-materials.
  14569. */
  14570. get: function () {
  14571. return this._facetDepthSort;
  14572. },
  14573. set: function (sort) {
  14574. this._facetDepthSort = sort;
  14575. },
  14576. enumerable: true,
  14577. configurable: true
  14578. });
  14579. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  14580. /**
  14581. * The location (Vector3) where the facet depth sort must be computed from.
  14582. * By default, the active camera position.
  14583. * Used only when facet depth sort is enabled.
  14584. */
  14585. get: function () {
  14586. return this._facetDepthSortFrom;
  14587. },
  14588. set: function (location) {
  14589. this._facetDepthSortFrom = location;
  14590. },
  14591. enumerable: true,
  14592. configurable: true
  14593. });
  14594. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  14595. /**
  14596. * Read-only boolean : is the feature facetData enabled ?
  14597. */
  14598. get: function () {
  14599. return this._facetDataEnabled;
  14600. },
  14601. enumerable: true,
  14602. configurable: true
  14603. });
  14604. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  14605. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  14606. return false;
  14607. }
  14608. this._markSubMeshesAsMiscDirty();
  14609. return true;
  14610. };
  14611. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  14612. set: function (callback) {
  14613. if (this._onCollideObserver) {
  14614. this.onCollideObservable.remove(this._onCollideObserver);
  14615. }
  14616. this._onCollideObserver = this.onCollideObservable.add(callback);
  14617. },
  14618. enumerable: true,
  14619. configurable: true
  14620. });
  14621. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  14622. set: function (callback) {
  14623. if (this._onCollisionPositionChangeObserver) {
  14624. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  14625. }
  14626. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  14627. },
  14628. enumerable: true,
  14629. configurable: true
  14630. });
  14631. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  14632. /**
  14633. * 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.
  14634. */
  14635. get: function () {
  14636. return this._isOccluded;
  14637. },
  14638. set: function (value) {
  14639. this._isOccluded = value;
  14640. },
  14641. enumerable: true,
  14642. configurable: true
  14643. });
  14644. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  14645. /**
  14646. * Flag to check the progress status of the query
  14647. */
  14648. get: function () {
  14649. return this._isOcclusionQueryInProgress;
  14650. },
  14651. enumerable: true,
  14652. configurable: true
  14653. });
  14654. Object.defineProperty(AbstractMesh.prototype, "material", {
  14655. get: function () {
  14656. return this._material;
  14657. },
  14658. set: function (value) {
  14659. if (this._material === value) {
  14660. return;
  14661. }
  14662. this._material = value;
  14663. if (this.onMaterialChangedObservable.hasObservers) {
  14664. this.onMaterialChangedObservable.notifyObservers(this);
  14665. }
  14666. if (!this.subMeshes) {
  14667. return;
  14668. }
  14669. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  14670. var subMesh = _a[_i];
  14671. subMesh.setEffect(null);
  14672. }
  14673. },
  14674. enumerable: true,
  14675. configurable: true
  14676. });
  14677. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  14678. get: function () {
  14679. return this._receiveShadows;
  14680. },
  14681. set: function (value) {
  14682. if (this._receiveShadows === value) {
  14683. return;
  14684. }
  14685. this._receiveShadows = value;
  14686. this._markSubMeshesAsLightDirty();
  14687. },
  14688. enumerable: true,
  14689. configurable: true
  14690. });
  14691. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  14692. get: function () {
  14693. return this._hasVertexAlpha;
  14694. },
  14695. set: function (value) {
  14696. if (this._hasVertexAlpha === value) {
  14697. return;
  14698. }
  14699. this._hasVertexAlpha = value;
  14700. this._markSubMeshesAsAttributesDirty();
  14701. },
  14702. enumerable: true,
  14703. configurable: true
  14704. });
  14705. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  14706. get: function () {
  14707. return this._useVertexColors;
  14708. },
  14709. set: function (value) {
  14710. if (this._useVertexColors === value) {
  14711. return;
  14712. }
  14713. this._useVertexColors = value;
  14714. this._markSubMeshesAsAttributesDirty();
  14715. },
  14716. enumerable: true,
  14717. configurable: true
  14718. });
  14719. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  14720. get: function () {
  14721. return this._computeBonesUsingShaders;
  14722. },
  14723. set: function (value) {
  14724. if (this._computeBonesUsingShaders === value) {
  14725. return;
  14726. }
  14727. this._computeBonesUsingShaders = value;
  14728. this._markSubMeshesAsAttributesDirty();
  14729. },
  14730. enumerable: true,
  14731. configurable: true
  14732. });
  14733. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  14734. get: function () {
  14735. return this._numBoneInfluencers;
  14736. },
  14737. set: function (value) {
  14738. if (this._numBoneInfluencers === value) {
  14739. return;
  14740. }
  14741. this._numBoneInfluencers = value;
  14742. this._markSubMeshesAsAttributesDirty();
  14743. },
  14744. enumerable: true,
  14745. configurable: true
  14746. });
  14747. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  14748. get: function () {
  14749. return this._applyFog;
  14750. },
  14751. set: function (value) {
  14752. if (this._applyFog === value) {
  14753. return;
  14754. }
  14755. this._applyFog = value;
  14756. this._markSubMeshesAsMiscDirty();
  14757. },
  14758. enumerable: true,
  14759. configurable: true
  14760. });
  14761. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  14762. get: function () {
  14763. return this._layerMask;
  14764. },
  14765. set: function (value) {
  14766. if (value === this._layerMask) {
  14767. return;
  14768. }
  14769. this._layerMask = value;
  14770. this._resyncLightSources();
  14771. },
  14772. enumerable: true,
  14773. configurable: true
  14774. });
  14775. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  14776. get: function () {
  14777. return this._collisionMask;
  14778. },
  14779. set: function (mask) {
  14780. this._collisionMask = !isNaN(mask) ? mask : -1;
  14781. },
  14782. enumerable: true,
  14783. configurable: true
  14784. });
  14785. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  14786. get: function () {
  14787. return this._collisionGroup;
  14788. },
  14789. set: function (mask) {
  14790. this._collisionGroup = !isNaN(mask) ? mask : -1;
  14791. },
  14792. enumerable: true,
  14793. configurable: true
  14794. });
  14795. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  14796. get: function () {
  14797. return null;
  14798. },
  14799. enumerable: true,
  14800. configurable: true
  14801. });
  14802. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  14803. get: function () {
  14804. return this._skeleton;
  14805. },
  14806. set: function (value) {
  14807. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  14808. this._skeleton._unregisterMeshWithPoseMatrix(this);
  14809. }
  14810. if (value && value.needInitialSkinMatrix) {
  14811. value._registerMeshWithPoseMatrix(this);
  14812. }
  14813. this._skeleton = value;
  14814. if (!this._skeleton) {
  14815. this._bonesTransformMatrices = null;
  14816. }
  14817. this._markSubMeshesAsAttributesDirty();
  14818. },
  14819. enumerable: true,
  14820. configurable: true
  14821. });
  14822. /**
  14823. * Boolean : true if the mesh has been disposed.
  14824. */
  14825. AbstractMesh.prototype.isDisposed = function () {
  14826. return this._isDisposed;
  14827. };
  14828. /**
  14829. * Returns the string "AbstractMesh"
  14830. */
  14831. AbstractMesh.prototype.getClassName = function () {
  14832. return "AbstractMesh";
  14833. };
  14834. /**
  14835. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  14836. */
  14837. AbstractMesh.prototype.toString = function (fullDetails) {
  14838. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  14839. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  14840. if (this._skeleton) {
  14841. ret += ", skeleton: " + this._skeleton.name;
  14842. }
  14843. if (fullDetails) {
  14844. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  14845. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  14846. }
  14847. return ret;
  14848. };
  14849. AbstractMesh.prototype._rebuild = function () {
  14850. if (this._occlusionQuery) {
  14851. this._occlusionQuery = null;
  14852. }
  14853. if (this._edgesRenderer) {
  14854. this._edgesRenderer._rebuild();
  14855. }
  14856. if (!this.subMeshes) {
  14857. return;
  14858. }
  14859. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  14860. var subMesh = _a[_i];
  14861. subMesh._rebuild();
  14862. }
  14863. };
  14864. AbstractMesh.prototype._resyncLightSources = function () {
  14865. this._lightSources.length = 0;
  14866. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  14867. var light = _a[_i];
  14868. if (!light.isEnabled()) {
  14869. continue;
  14870. }
  14871. if (light.canAffectMesh(this)) {
  14872. this._lightSources.push(light);
  14873. }
  14874. }
  14875. this._markSubMeshesAsLightDirty();
  14876. };
  14877. AbstractMesh.prototype._resyncLighSource = function (light) {
  14878. var isIn = light.isEnabled() && light.canAffectMesh(this);
  14879. var index = this._lightSources.indexOf(light);
  14880. if (index === -1) {
  14881. if (!isIn) {
  14882. return;
  14883. }
  14884. this._lightSources.push(light);
  14885. }
  14886. else {
  14887. if (isIn) {
  14888. return;
  14889. }
  14890. this._lightSources.splice(index, 1);
  14891. }
  14892. this._markSubMeshesAsLightDirty();
  14893. };
  14894. AbstractMesh.prototype._removeLightSource = function (light) {
  14895. var index = this._lightSources.indexOf(light);
  14896. if (index === -1) {
  14897. return;
  14898. }
  14899. this._lightSources.splice(index, 1);
  14900. };
  14901. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  14902. if (!this.subMeshes) {
  14903. return;
  14904. }
  14905. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  14906. var subMesh = _a[_i];
  14907. if (subMesh._materialDefines) {
  14908. func(subMesh._materialDefines);
  14909. }
  14910. }
  14911. };
  14912. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  14913. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  14914. };
  14915. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  14916. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  14917. };
  14918. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  14919. if (!this.subMeshes) {
  14920. return;
  14921. }
  14922. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  14923. var subMesh = _a[_i];
  14924. var material = subMesh.getMaterial();
  14925. if (material) {
  14926. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  14927. }
  14928. }
  14929. };
  14930. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  14931. /**
  14932. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  14933. * Default : (1.0, 1.0, 1.0)
  14934. */
  14935. get: function () {
  14936. return this._scaling;
  14937. },
  14938. /**
  14939. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  14940. * Default : (1.0, 1.0, 1.0)
  14941. */
  14942. set: function (newScaling) {
  14943. this._scaling = newScaling;
  14944. if (this.physicsImpostor) {
  14945. this.physicsImpostor.forceUpdate();
  14946. }
  14947. },
  14948. enumerable: true,
  14949. configurable: true
  14950. });
  14951. // Methods
  14952. /**
  14953. * Disables the mesh edger rendering mode.
  14954. * Returns the AbstractMesh.
  14955. */
  14956. AbstractMesh.prototype.disableEdgesRendering = function () {
  14957. if (this._edgesRenderer) {
  14958. this._edgesRenderer.dispose();
  14959. this._edgesRenderer = null;
  14960. }
  14961. return this;
  14962. };
  14963. /**
  14964. * Enables the edge rendering mode on the mesh.
  14965. * This mode makes the mesh edges visible.
  14966. * Returns the AbstractMesh.
  14967. */
  14968. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  14969. if (epsilon === void 0) { epsilon = 0.95; }
  14970. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  14971. this.disableEdgesRendering();
  14972. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  14973. return this;
  14974. };
  14975. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  14976. /**
  14977. * Returns true if the mesh is blocked. Used by the class Mesh.
  14978. * Returns the boolean `false` by default.
  14979. */
  14980. get: function () {
  14981. return false;
  14982. },
  14983. enumerable: true,
  14984. configurable: true
  14985. });
  14986. /**
  14987. * Returns the mesh itself by default, used by the class Mesh.
  14988. * Returned type : AbstractMesh
  14989. */
  14990. AbstractMesh.prototype.getLOD = function (camera) {
  14991. return this;
  14992. };
  14993. /**
  14994. * Returns 0 by default, used by the class Mesh.
  14995. * Returns an integer.
  14996. */
  14997. AbstractMesh.prototype.getTotalVertices = function () {
  14998. return 0;
  14999. };
  15000. /**
  15001. * Returns null by default, used by the class Mesh.
  15002. * Returned type : integer array
  15003. */
  15004. AbstractMesh.prototype.getIndices = function () {
  15005. return null;
  15006. };
  15007. /**
  15008. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  15009. * Returned type : float array or Float32Array
  15010. */
  15011. AbstractMesh.prototype.getVerticesData = function (kind) {
  15012. return null;
  15013. };
  15014. /**
  15015. * Sets the vertex data of the mesh geometry for the requested `kind`.
  15016. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  15017. * The `data` are either a numeric array either a Float32Array.
  15018. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  15019. * 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).
  15020. * Note that a new underlying VertexBuffer object is created each call.
  15021. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  15022. *
  15023. * Possible `kind` values :
  15024. * - BABYLON.VertexBuffer.PositionKind
  15025. * - BABYLON.VertexBuffer.UVKind
  15026. * - BABYLON.VertexBuffer.UV2Kind
  15027. * - BABYLON.VertexBuffer.UV3Kind
  15028. * - BABYLON.VertexBuffer.UV4Kind
  15029. * - BABYLON.VertexBuffer.UV5Kind
  15030. * - BABYLON.VertexBuffer.UV6Kind
  15031. * - BABYLON.VertexBuffer.ColorKind
  15032. * - BABYLON.VertexBuffer.MatricesIndicesKind
  15033. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  15034. * - BABYLON.VertexBuffer.MatricesWeightsKind
  15035. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  15036. *
  15037. * Returns the Mesh.
  15038. */
  15039. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  15040. return this;
  15041. };
  15042. /**
  15043. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  15044. * If the mesh has no geometry, it is simply returned as it is.
  15045. * The `data` are either a numeric array either a Float32Array.
  15046. * No new underlying VertexBuffer object is created.
  15047. * 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.
  15048. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  15049. *
  15050. * Possible `kind` values :
  15051. * - BABYLON.VertexBuffer.PositionKind
  15052. * - BABYLON.VertexBuffer.UVKind
  15053. * - BABYLON.VertexBuffer.UV2Kind
  15054. * - BABYLON.VertexBuffer.UV3Kind
  15055. * - BABYLON.VertexBuffer.UV4Kind
  15056. * - BABYLON.VertexBuffer.UV5Kind
  15057. * - BABYLON.VertexBuffer.UV6Kind
  15058. * - BABYLON.VertexBuffer.ColorKind
  15059. * - BABYLON.VertexBuffer.MatricesIndicesKind
  15060. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  15061. * - BABYLON.VertexBuffer.MatricesWeightsKind
  15062. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  15063. *
  15064. * Returns the Mesh.
  15065. */
  15066. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  15067. return this;
  15068. };
  15069. /**
  15070. * Sets the mesh indices.
  15071. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  15072. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  15073. * This method creates a new index buffer each call.
  15074. * Returns the Mesh.
  15075. */
  15076. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  15077. return this;
  15078. };
  15079. /** Returns false by default, used by the class Mesh.
  15080. * Returns a boolean
  15081. */
  15082. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  15083. return false;
  15084. };
  15085. /**
  15086. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  15087. * Returns a BoundingInfo
  15088. */
  15089. AbstractMesh.prototype.getBoundingInfo = function () {
  15090. if (this._masterMesh) {
  15091. return this._masterMesh.getBoundingInfo();
  15092. }
  15093. if (!this._boundingInfo) {
  15094. // this._boundingInfo is being created here
  15095. this._updateBoundingInfo();
  15096. }
  15097. // cannot be null.
  15098. return this._boundingInfo;
  15099. };
  15100. /**
  15101. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units).
  15102. * @param includeDescendants Take the hierarchy's bounding box instead of the mesh's bounding box.
  15103. */
  15104. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  15105. if (includeDescendants === void 0) { includeDescendants = true; }
  15106. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  15107. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  15108. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  15109. if (maxDimension === 0) {
  15110. return this;
  15111. }
  15112. var scale = 1 / maxDimension;
  15113. this.scaling.scaleInPlace(scale);
  15114. return this;
  15115. };
  15116. /**
  15117. * Sets a mesh new object BoundingInfo.
  15118. * Returns the AbstractMesh.
  15119. */
  15120. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  15121. this._boundingInfo = boundingInfo;
  15122. return this;
  15123. };
  15124. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  15125. get: function () {
  15126. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  15127. },
  15128. enumerable: true,
  15129. configurable: true
  15130. });
  15131. AbstractMesh.prototype._preActivate = function () {
  15132. };
  15133. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  15134. };
  15135. AbstractMesh.prototype._activate = function (renderId) {
  15136. this._renderId = renderId;
  15137. };
  15138. /**
  15139. * Returns the latest update of the World matrix
  15140. * Returns a Matrix.
  15141. */
  15142. AbstractMesh.prototype.getWorldMatrix = function () {
  15143. if (this._masterMesh) {
  15144. return this._masterMesh.getWorldMatrix();
  15145. }
  15146. return _super.prototype.getWorldMatrix.call(this);
  15147. };
  15148. /**
  15149. * Returns the latest update of the World matrix determinant.
  15150. */
  15151. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  15152. if (this._masterMesh) {
  15153. return this._masterMesh._getWorldMatrixDeterminant();
  15154. }
  15155. return _super.prototype._getWorldMatrixDeterminant.call(this);
  15156. };
  15157. // ================================== Point of View Movement =================================
  15158. /**
  15159. * Perform relative position change from the point of view of behind the front of the mesh.
  15160. * This is performed taking into account the meshes current rotation, so you do not have to care.
  15161. * Supports definition of mesh facing forward or backward.
  15162. * @param {number} amountRight
  15163. * @param {number} amountUp
  15164. * @param {number} amountForward
  15165. *
  15166. * Returns the AbstractMesh.
  15167. */
  15168. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  15169. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  15170. return this;
  15171. };
  15172. /**
  15173. * Calculate relative position change from the point of view of behind the front of the mesh.
  15174. * This is performed taking into account the meshes current rotation, so you do not have to care.
  15175. * Supports definition of mesh facing forward or backward.
  15176. * @param {number} amountRight
  15177. * @param {number} amountUp
  15178. * @param {number} amountForward
  15179. *
  15180. * Returns a new Vector3.
  15181. */
  15182. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  15183. var rotMatrix = new BABYLON.Matrix();
  15184. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  15185. rotQuaternion.toRotationMatrix(rotMatrix);
  15186. var translationDelta = BABYLON.Vector3.Zero();
  15187. var defForwardMult = this.definedFacingForward ? -1 : 1;
  15188. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  15189. return translationDelta;
  15190. };
  15191. // ================================== Point of View Rotation =================================
  15192. /**
  15193. * Perform relative rotation change from the point of view of behind the front of the mesh.
  15194. * Supports definition of mesh facing forward or backward.
  15195. * @param {number} flipBack
  15196. * @param {number} twirlClockwise
  15197. * @param {number} tiltRight
  15198. *
  15199. * Returns the AbstractMesh.
  15200. */
  15201. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  15202. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  15203. return this;
  15204. };
  15205. /**
  15206. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  15207. * Supports definition of mesh facing forward or backward.
  15208. * @param {number} flipBack
  15209. * @param {number} twirlClockwise
  15210. * @param {number} tiltRight
  15211. *
  15212. * Returns a new Vector3.
  15213. */
  15214. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  15215. var defForwardMult = this.definedFacingForward ? 1 : -1;
  15216. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  15217. };
  15218. /**
  15219. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  15220. * @param includeDescendants Include bounding info from descendants as well (true by default).
  15221. */
  15222. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants) {
  15223. if (includeDescendants === void 0) { includeDescendants = true; }
  15224. this.computeWorldMatrix(true);
  15225. var min;
  15226. var max;
  15227. var boundingInfo = this.getBoundingInfo();
  15228. if (!this.subMeshes) {
  15229. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  15230. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  15231. }
  15232. else {
  15233. min = boundingInfo.boundingBox.minimumWorld;
  15234. max = boundingInfo.boundingBox.maximumWorld;
  15235. }
  15236. if (includeDescendants) {
  15237. var descendants = this.getDescendants(false);
  15238. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  15239. var descendant = descendants_1[_i];
  15240. var childMesh = descendant;
  15241. childMesh.computeWorldMatrix(true);
  15242. //make sure we have the needed params to get mix and max
  15243. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  15244. continue;
  15245. }
  15246. var childBoundingInfo = childMesh.getBoundingInfo();
  15247. var boundingBox = childBoundingInfo.boundingBox;
  15248. var minBox = boundingBox.minimumWorld;
  15249. var maxBox = boundingBox.maximumWorld;
  15250. BABYLON.Tools.CheckExtends(minBox, min, max);
  15251. BABYLON.Tools.CheckExtends(maxBox, min, max);
  15252. }
  15253. }
  15254. return {
  15255. min: min,
  15256. max: max
  15257. };
  15258. };
  15259. /**
  15260. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  15261. * Returns the AbstractMesh.
  15262. */
  15263. AbstractMesh.prototype._updateBoundingInfo = function () {
  15264. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  15265. this._boundingInfo.update(this.worldMatrixFromCache);
  15266. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  15267. return this;
  15268. };
  15269. /**
  15270. * Update a mesh's children BoundingInfo objects only.
  15271. * Returns the AbstractMesh.
  15272. */
  15273. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  15274. if (!this.subMeshes) {
  15275. return this;
  15276. }
  15277. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  15278. var subMesh = this.subMeshes[subIndex];
  15279. if (!subMesh.IsGlobal) {
  15280. subMesh.updateBoundingInfo(matrix);
  15281. }
  15282. }
  15283. return this;
  15284. };
  15285. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  15286. // Bounding info
  15287. this._updateBoundingInfo();
  15288. };
  15289. /**
  15290. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  15291. * A mesh is in the frustum if its bounding box intersects the frustum.
  15292. * Boolean returned.
  15293. */
  15294. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  15295. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  15296. };
  15297. /**
  15298. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  15299. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  15300. * Boolean returned.
  15301. */
  15302. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  15303. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  15304. ;
  15305. };
  15306. /**
  15307. * True if the mesh intersects another mesh or a SolidParticle object.
  15308. * 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)
  15309. * includeDescendants can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  15310. * Returns a boolean.
  15311. */
  15312. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  15313. if (precise === void 0) { precise = false; }
  15314. if (!this._boundingInfo || !mesh._boundingInfo) {
  15315. return false;
  15316. }
  15317. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  15318. return true;
  15319. }
  15320. if (includeDescendants) {
  15321. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  15322. var child = _a[_i];
  15323. if (child.intersectsMesh(mesh, precise, true)) {
  15324. return true;
  15325. }
  15326. }
  15327. }
  15328. return false;
  15329. };
  15330. /**
  15331. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  15332. * Returns a boolean.
  15333. */
  15334. AbstractMesh.prototype.intersectsPoint = function (point) {
  15335. if (!this._boundingInfo) {
  15336. return false;
  15337. }
  15338. return this._boundingInfo.intersectsPoint(point);
  15339. };
  15340. AbstractMesh.prototype.getPhysicsImpostor = function () {
  15341. return this.physicsImpostor;
  15342. };
  15343. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  15344. if (camera === void 0) { camera = null; }
  15345. if (!camera) {
  15346. camera = this.getScene().activeCamera;
  15347. }
  15348. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  15349. };
  15350. /**
  15351. * Returns the distance from the mesh to the active camera.
  15352. * Returns a float.
  15353. */
  15354. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  15355. if (camera === void 0) { camera = null; }
  15356. if (!camera) {
  15357. camera = this.getScene().activeCamera;
  15358. }
  15359. return this.absolutePosition.subtract(camera.position).length();
  15360. };
  15361. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  15362. if (!this.physicsImpostor) {
  15363. return this;
  15364. }
  15365. this.physicsImpostor.applyImpulse(force, contactPoint);
  15366. return this;
  15367. };
  15368. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  15369. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  15370. return this;
  15371. }
  15372. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  15373. mainPivot: pivot1,
  15374. connectedPivot: pivot2,
  15375. nativeParams: options
  15376. });
  15377. return this;
  15378. };
  15379. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  15380. // Collisions
  15381. /**
  15382. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  15383. * Default `false`.
  15384. */
  15385. get: function () {
  15386. return this._checkCollisions;
  15387. },
  15388. set: function (collisionEnabled) {
  15389. this._checkCollisions = collisionEnabled;
  15390. if (this.getScene().workerCollisions) {
  15391. this.getScene().collisionCoordinator.onMeshUpdated(this);
  15392. }
  15393. },
  15394. enumerable: true,
  15395. configurable: true
  15396. });
  15397. Object.defineProperty(AbstractMesh.prototype, "collider", {
  15398. /**
  15399. * Gets Collider object used to compute collisions (not physics)
  15400. */
  15401. get: function () {
  15402. return this._collider;
  15403. },
  15404. enumerable: true,
  15405. configurable: true
  15406. });
  15407. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  15408. var globalPosition = this.getAbsolutePosition();
  15409. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  15410. if (!this._collider) {
  15411. this._collider = new BABYLON.Collider();
  15412. }
  15413. this._collider._radius = this.ellipsoid;
  15414. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  15415. return this;
  15416. };
  15417. // Submeshes octree
  15418. /**
  15419. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  15420. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  15421. * Returns an Octree of submeshes.
  15422. */
  15423. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  15424. if (maxCapacity === void 0) { maxCapacity = 64; }
  15425. if (maxDepth === void 0) { maxDepth = 2; }
  15426. if (!this._submeshesOctree) {
  15427. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  15428. }
  15429. this.computeWorldMatrix(true);
  15430. var boundingInfo = this.getBoundingInfo();
  15431. // Update octree
  15432. var bbox = boundingInfo.boundingBox;
  15433. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  15434. return this._submeshesOctree;
  15435. };
  15436. // Collisions
  15437. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  15438. this._generatePointsArray();
  15439. if (!this._positions) {
  15440. return this;
  15441. }
  15442. // Transformation
  15443. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  15444. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  15445. subMesh._lastColliderWorldVertices = [];
  15446. subMesh._trianglePlanes = [];
  15447. var start = subMesh.verticesStart;
  15448. var end = (subMesh.verticesStart + subMesh.verticesCount);
  15449. for (var i = start; i < end; i++) {
  15450. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  15451. }
  15452. }
  15453. // Collide
  15454. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  15455. if (collider.collisionFound) {
  15456. collider.collidedMesh = this;
  15457. }
  15458. return this;
  15459. };
  15460. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  15461. var subMeshes;
  15462. var len;
  15463. // Octrees
  15464. if (this._submeshesOctree && this.useOctreeForCollisions) {
  15465. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  15466. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  15467. len = intersections.length;
  15468. subMeshes = intersections.data;
  15469. }
  15470. else {
  15471. subMeshes = this.subMeshes;
  15472. len = subMeshes.length;
  15473. }
  15474. for (var index = 0; index < len; index++) {
  15475. var subMesh = subMeshes[index];
  15476. // Bounding test
  15477. if (len > 1 && !subMesh._checkCollision(collider))
  15478. continue;
  15479. this._collideForSubMesh(subMesh, transformMatrix, collider);
  15480. }
  15481. return this;
  15482. };
  15483. AbstractMesh.prototype._checkCollision = function (collider) {
  15484. // Bounding box test
  15485. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  15486. return this;
  15487. // Transformation matrix
  15488. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  15489. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  15490. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  15491. return this;
  15492. };
  15493. // Picking
  15494. AbstractMesh.prototype._generatePointsArray = function () {
  15495. return false;
  15496. };
  15497. /**
  15498. * Checks if the passed Ray intersects with the mesh.
  15499. * Returns an object PickingInfo.
  15500. */
  15501. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  15502. var pickingInfo = new BABYLON.PickingInfo();
  15503. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  15504. return pickingInfo;
  15505. }
  15506. if (!this._generatePointsArray()) {
  15507. return pickingInfo;
  15508. }
  15509. var intersectInfo = null;
  15510. // Octrees
  15511. var subMeshes;
  15512. var len;
  15513. if (this._submeshesOctree && this.useOctreeForPicking) {
  15514. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  15515. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  15516. len = intersections.length;
  15517. subMeshes = intersections.data;
  15518. }
  15519. else {
  15520. subMeshes = this.subMeshes;
  15521. len = subMeshes.length;
  15522. }
  15523. for (var index = 0; index < len; index++) {
  15524. var subMesh = subMeshes[index];
  15525. // Bounding test
  15526. if (len > 1 && !subMesh.canIntersects(ray))
  15527. continue;
  15528. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  15529. if (currentIntersectInfo) {
  15530. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  15531. intersectInfo = currentIntersectInfo;
  15532. intersectInfo.subMeshId = index;
  15533. if (fastCheck) {
  15534. break;
  15535. }
  15536. }
  15537. }
  15538. }
  15539. if (intersectInfo) {
  15540. // Get picked point
  15541. var world = this.getWorldMatrix();
  15542. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  15543. var direction = ray.direction.clone();
  15544. direction = direction.scale(intersectInfo.distance);
  15545. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  15546. var pickedPoint = worldOrigin.add(worldDirection);
  15547. // Return result
  15548. pickingInfo.hit = true;
  15549. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  15550. pickingInfo.pickedPoint = pickedPoint;
  15551. pickingInfo.pickedMesh = this;
  15552. pickingInfo.bu = intersectInfo.bu || 0;
  15553. pickingInfo.bv = intersectInfo.bv || 0;
  15554. pickingInfo.faceId = intersectInfo.faceId;
  15555. pickingInfo.subMeshId = intersectInfo.subMeshId;
  15556. return pickingInfo;
  15557. }
  15558. return pickingInfo;
  15559. };
  15560. /**
  15561. * Clones the mesh, used by the class Mesh.
  15562. * Just returns `null` for an AbstractMesh.
  15563. */
  15564. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  15565. return null;
  15566. };
  15567. /**
  15568. * Disposes all the mesh submeshes.
  15569. * Returns the AbstractMesh.
  15570. */
  15571. AbstractMesh.prototype.releaseSubMeshes = function () {
  15572. if (this.subMeshes) {
  15573. while (this.subMeshes.length) {
  15574. this.subMeshes[0].dispose();
  15575. }
  15576. }
  15577. else {
  15578. this.subMeshes = new Array();
  15579. }
  15580. return this;
  15581. };
  15582. /**
  15583. * Disposes the AbstractMesh.
  15584. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  15585. * Returns nothing.
  15586. */
  15587. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  15588. var _this = this;
  15589. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  15590. var index;
  15591. // Action manager
  15592. if (this.actionManager !== undefined && this.actionManager !== null) {
  15593. this.actionManager.dispose();
  15594. this.actionManager = null;
  15595. }
  15596. // Skeleton
  15597. this.skeleton = null;
  15598. // Physics
  15599. if (this.physicsImpostor) {
  15600. this.physicsImpostor.dispose();
  15601. }
  15602. // Intersections in progress
  15603. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  15604. var other = this._intersectionsInProgress[index];
  15605. var pos = other._intersectionsInProgress.indexOf(this);
  15606. other._intersectionsInProgress.splice(pos, 1);
  15607. }
  15608. this._intersectionsInProgress = [];
  15609. // Lights
  15610. var lights = this.getScene().lights;
  15611. lights.forEach(function (light) {
  15612. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  15613. if (meshIndex !== -1) {
  15614. light.includedOnlyMeshes.splice(meshIndex, 1);
  15615. }
  15616. meshIndex = light.excludedMeshes.indexOf(_this);
  15617. if (meshIndex !== -1) {
  15618. light.excludedMeshes.splice(meshIndex, 1);
  15619. }
  15620. // Shadow generators
  15621. var generator = light.getShadowGenerator();
  15622. if (generator) {
  15623. var shadowMap = generator.getShadowMap();
  15624. if (shadowMap && shadowMap.renderList) {
  15625. meshIndex = shadowMap.renderList.indexOf(_this);
  15626. if (meshIndex !== -1) {
  15627. shadowMap.renderList.splice(meshIndex, 1);
  15628. }
  15629. }
  15630. }
  15631. });
  15632. // Edges
  15633. if (this._edgesRenderer) {
  15634. this._edgesRenderer.dispose();
  15635. this._edgesRenderer = null;
  15636. }
  15637. // SubMeshes
  15638. if (this.getClassName() !== "InstancedMesh") {
  15639. this.releaseSubMeshes();
  15640. }
  15641. // Octree
  15642. var sceneOctree = this.getScene().selectionOctree;
  15643. if (sceneOctree !== undefined && sceneOctree !== null) {
  15644. var index = sceneOctree.dynamicContent.indexOf(this);
  15645. if (index !== -1) {
  15646. sceneOctree.dynamicContent.splice(index, 1);
  15647. }
  15648. }
  15649. // Query
  15650. var engine = this.getScene().getEngine();
  15651. if (this._occlusionQuery) {
  15652. this._isOcclusionQueryInProgress = false;
  15653. engine.deleteQuery(this._occlusionQuery);
  15654. this._occlusionQuery = null;
  15655. }
  15656. // Engine
  15657. engine.wipeCaches();
  15658. // Remove from scene
  15659. this.getScene().removeMesh(this);
  15660. if (disposeMaterialAndTextures) {
  15661. if (this.material) {
  15662. this.material.dispose(false, true);
  15663. }
  15664. }
  15665. if (!doNotRecurse) {
  15666. // Particles
  15667. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  15668. if (this.getScene().particleSystems[index].emitter === this) {
  15669. this.getScene().particleSystems[index].dispose();
  15670. index--;
  15671. }
  15672. }
  15673. }
  15674. // facet data
  15675. if (this._facetDataEnabled) {
  15676. this.disableFacetData();
  15677. }
  15678. this.onAfterWorldMatrixUpdateObservable.clear();
  15679. this.onCollideObservable.clear();
  15680. this.onCollisionPositionChangeObservable.clear();
  15681. this._isDisposed = true;
  15682. _super.prototype.dispose.call(this, doNotRecurse);
  15683. };
  15684. /**
  15685. * Adds the passed mesh as a child to the current mesh.
  15686. * Returns the AbstractMesh.
  15687. */
  15688. AbstractMesh.prototype.addChild = function (mesh) {
  15689. mesh.setParent(this);
  15690. return this;
  15691. };
  15692. /**
  15693. * Removes the passed mesh from the current mesh children list.
  15694. * Returns the AbstractMesh.
  15695. */
  15696. AbstractMesh.prototype.removeChild = function (mesh) {
  15697. mesh.setParent(null);
  15698. return this;
  15699. };
  15700. // Facet data
  15701. /**
  15702. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  15703. * Returns the AbstractMesh.
  15704. */
  15705. AbstractMesh.prototype._initFacetData = function () {
  15706. if (!this._facetNormals) {
  15707. this._facetNormals = new Array();
  15708. }
  15709. if (!this._facetPositions) {
  15710. this._facetPositions = new Array();
  15711. }
  15712. if (!this._facetPartitioning) {
  15713. this._facetPartitioning = new Array();
  15714. }
  15715. this._facetNb = (this.getIndices().length / 3) | 0;
  15716. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  15717. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  15718. for (var f = 0; f < this._facetNb; f++) {
  15719. this._facetNormals[f] = BABYLON.Vector3.Zero();
  15720. this._facetPositions[f] = BABYLON.Vector3.Zero();
  15721. }
  15722. this._facetDataEnabled = true;
  15723. return this;
  15724. };
  15725. /**
  15726. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  15727. * This method can be called within the render loop.
  15728. * 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.
  15729. * Returns the AbstractMesh.
  15730. */
  15731. AbstractMesh.prototype.updateFacetData = function () {
  15732. if (!this._facetDataEnabled) {
  15733. this._initFacetData();
  15734. }
  15735. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15736. var indices = this.getIndices();
  15737. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15738. var bInfo = this.getBoundingInfo();
  15739. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  15740. // init arrays, matrix and sort function on first call
  15741. this._facetDepthSortEnabled = true;
  15742. if (indices instanceof Uint16Array) {
  15743. this._depthSortedIndices = new Uint16Array(indices);
  15744. }
  15745. else if (indices instanceof Uint32Array) {
  15746. this._depthSortedIndices = new Uint32Array(indices);
  15747. }
  15748. else {
  15749. var needs32bits = false;
  15750. for (var i = 0; i < indices.length; i++) {
  15751. if (indices[i] > 65535) {
  15752. needs32bits = true;
  15753. break;
  15754. }
  15755. }
  15756. if (needs32bits) {
  15757. this._depthSortedIndices = new Uint32Array(indices);
  15758. }
  15759. else {
  15760. this._depthSortedIndices = new Uint16Array(indices);
  15761. }
  15762. }
  15763. this._facetDepthSortFunction = function (f1, f2) {
  15764. return (f2.sqDistance - f1.sqDistance);
  15765. };
  15766. if (!this._facetDepthSortFrom) {
  15767. var camera = this.getScene().activeCamera;
  15768. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  15769. }
  15770. this._depthSortedFacets = [];
  15771. for (var f = 0; f < this._facetNb; f++) {
  15772. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  15773. this._depthSortedFacets.push(depthSortedFacet);
  15774. }
  15775. this._invertedMatrix = BABYLON.Matrix.Identity();
  15776. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  15777. }
  15778. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  15779. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  15780. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  15781. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  15782. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  15783. this._subDiv.max = this._partitioningSubdivisions;
  15784. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  15785. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  15786. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  15787. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  15788. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  15789. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  15790. // set the parameters for ComputeNormals()
  15791. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  15792. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  15793. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  15794. this._facetParameters.bInfo = bInfo;
  15795. this._facetParameters.bbSize = this._bbSize;
  15796. this._facetParameters.subDiv = this._subDiv;
  15797. this._facetParameters.ratio = this.partitioningBBoxRatio;
  15798. this._facetParameters.depthSort = this._facetDepthSort;
  15799. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  15800. this.computeWorldMatrix(true);
  15801. this._worldMatrix.invertToRef(this._invertedMatrix);
  15802. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  15803. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  15804. }
  15805. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  15806. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  15807. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  15808. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  15809. var l = (this._depthSortedIndices.length / 3) | 0;
  15810. for (var f = 0; f < l; f++) {
  15811. var sind = this._depthSortedFacets[f].ind;
  15812. this._depthSortedIndices[f * 3] = indices[sind];
  15813. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  15814. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  15815. }
  15816. this.updateIndices(this._depthSortedIndices);
  15817. }
  15818. return this;
  15819. };
  15820. /**
  15821. * Returns the facetLocalNormals array.
  15822. * The normals are expressed in the mesh local space.
  15823. */
  15824. AbstractMesh.prototype.getFacetLocalNormals = function () {
  15825. if (!this._facetNormals) {
  15826. this.updateFacetData();
  15827. }
  15828. return this._facetNormals;
  15829. };
  15830. /**
  15831. * Returns the facetLocalPositions array.
  15832. * The facet positions are expressed in the mesh local space.
  15833. */
  15834. AbstractMesh.prototype.getFacetLocalPositions = function () {
  15835. if (!this._facetPositions) {
  15836. this.updateFacetData();
  15837. }
  15838. return this._facetPositions;
  15839. };
  15840. /**
  15841. * Returns the facetLocalPartioning array.
  15842. */
  15843. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  15844. if (!this._facetPartitioning) {
  15845. this.updateFacetData();
  15846. }
  15847. return this._facetPartitioning;
  15848. };
  15849. /**
  15850. * Returns the i-th facet position in the world system.
  15851. * This method allocates a new Vector3 per call.
  15852. */
  15853. AbstractMesh.prototype.getFacetPosition = function (i) {
  15854. var pos = BABYLON.Vector3.Zero();
  15855. this.getFacetPositionToRef(i, pos);
  15856. return pos;
  15857. };
  15858. /**
  15859. * Sets the reference Vector3 with the i-th facet position in the world system.
  15860. * Returns the AbstractMesh.
  15861. */
  15862. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  15863. var localPos = (this.getFacetLocalPositions())[i];
  15864. var world = this.getWorldMatrix();
  15865. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  15866. return this;
  15867. };
  15868. /**
  15869. * Returns the i-th facet normal in the world system.
  15870. * This method allocates a new Vector3 per call.
  15871. */
  15872. AbstractMesh.prototype.getFacetNormal = function (i) {
  15873. var norm = BABYLON.Vector3.Zero();
  15874. this.getFacetNormalToRef(i, norm);
  15875. return norm;
  15876. };
  15877. /**
  15878. * Sets the reference Vector3 with the i-th facet normal in the world system.
  15879. * Returns the AbstractMesh.
  15880. */
  15881. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  15882. var localNorm = (this.getFacetLocalNormals())[i];
  15883. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  15884. return this;
  15885. };
  15886. /**
  15887. * 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).
  15888. */
  15889. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  15890. var bInfo = this.getBoundingInfo();
  15891. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  15892. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  15893. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  15894. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  15895. return null;
  15896. }
  15897. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  15898. };
  15899. /**
  15900. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  15901. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  15902. * 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.
  15903. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  15904. * 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.
  15905. */
  15906. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  15907. if (checkFace === void 0) { checkFace = false; }
  15908. if (facing === void 0) { facing = true; }
  15909. var world = this.getWorldMatrix();
  15910. var invMat = BABYLON.Tmp.Matrix[5];
  15911. world.invertToRef(invMat);
  15912. var invVect = BABYLON.Tmp.Vector3[8];
  15913. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  15914. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  15915. if (projected) {
  15916. // tranform the local computed projected vector to world coordinates
  15917. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  15918. }
  15919. return closest;
  15920. };
  15921. /**
  15922. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  15923. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  15924. * 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.
  15925. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  15926. * 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.
  15927. */
  15928. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  15929. if (checkFace === void 0) { checkFace = false; }
  15930. if (facing === void 0) { facing = true; }
  15931. var closest = null;
  15932. var tmpx = 0.0;
  15933. var tmpy = 0.0;
  15934. var tmpz = 0.0;
  15935. var d = 0.0; // tmp dot facet normal * facet position
  15936. var t0 = 0.0;
  15937. var projx = 0.0;
  15938. var projy = 0.0;
  15939. var projz = 0.0;
  15940. // Get all the facets in the same partitioning block than (x, y, z)
  15941. var facetPositions = this.getFacetLocalPositions();
  15942. var facetNormals = this.getFacetLocalNormals();
  15943. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  15944. if (!facetsInBlock) {
  15945. return null;
  15946. }
  15947. // Get the closest facet to (x, y, z)
  15948. var shortest = Number.MAX_VALUE; // init distance vars
  15949. var tmpDistance = shortest;
  15950. var fib; // current facet in the block
  15951. var norm; // current facet normal
  15952. var p0; // current facet barycenter position
  15953. // loop on all the facets in the current partitioning block
  15954. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  15955. fib = facetsInBlock[idx];
  15956. norm = facetNormals[fib];
  15957. p0 = facetPositions[fib];
  15958. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  15959. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  15960. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  15961. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  15962. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  15963. projx = x + norm.x * t0;
  15964. projy = y + norm.y * t0;
  15965. projz = z + norm.z * t0;
  15966. tmpx = projx - x;
  15967. tmpy = projy - y;
  15968. tmpz = projz - z;
  15969. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  15970. if (tmpDistance < shortest) {
  15971. shortest = tmpDistance;
  15972. closest = fib;
  15973. if (projected) {
  15974. projected.x = projx;
  15975. projected.y = projy;
  15976. projected.z = projz;
  15977. }
  15978. }
  15979. }
  15980. }
  15981. return closest;
  15982. };
  15983. /**
  15984. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  15985. */
  15986. AbstractMesh.prototype.getFacetDataParameters = function () {
  15987. return this._facetParameters;
  15988. };
  15989. /**
  15990. * Disables the feature FacetData and frees the related memory.
  15991. * Returns the AbstractMesh.
  15992. */
  15993. AbstractMesh.prototype.disableFacetData = function () {
  15994. if (this._facetDataEnabled) {
  15995. this._facetDataEnabled = false;
  15996. this._facetPositions = new Array();
  15997. this._facetNormals = new Array();
  15998. this._facetPartitioning = new Array();
  15999. this._facetParameters = null;
  16000. this._depthSortedIndices = new Uint32Array(0);
  16001. }
  16002. return this;
  16003. };
  16004. /**
  16005. * Updates the AbstractMesh indices array. Actually, used by the Mesh object.
  16006. * Returns the mesh.
  16007. */
  16008. AbstractMesh.prototype.updateIndices = function (indices) {
  16009. return this;
  16010. };
  16011. /**
  16012. * The mesh Geometry. Actually used by the Mesh object.
  16013. * Returns a blank geometry object.
  16014. */
  16015. /**
  16016. * Creates new normals data for the mesh.
  16017. * @param updatable.
  16018. */
  16019. AbstractMesh.prototype.createNormals = function (updatable) {
  16020. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16021. var indices = this.getIndices();
  16022. var normals;
  16023. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  16024. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16025. }
  16026. else {
  16027. normals = [];
  16028. }
  16029. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  16030. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  16031. };
  16032. /**
  16033. * Align the mesh with a normal.
  16034. * Returns the mesh.
  16035. */
  16036. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  16037. if (!upDirection) {
  16038. upDirection = BABYLON.Axis.Y;
  16039. }
  16040. var axisX = BABYLON.Tmp.Vector3[0];
  16041. var axisZ = BABYLON.Tmp.Vector3[1];
  16042. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  16043. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  16044. if (this.rotationQuaternion) {
  16045. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  16046. }
  16047. else {
  16048. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  16049. }
  16050. return this;
  16051. };
  16052. AbstractMesh.prototype.checkOcclusionQuery = function () {
  16053. var engine = this.getEngine();
  16054. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  16055. this._isOccluded = false;
  16056. return;
  16057. }
  16058. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  16059. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  16060. if (isOcclusionQueryAvailable) {
  16061. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  16062. this._isOcclusionQueryInProgress = false;
  16063. this._occlusionInternalRetryCounter = 0;
  16064. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  16065. }
  16066. else {
  16067. this._occlusionInternalRetryCounter++;
  16068. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  16069. this._isOcclusionQueryInProgress = false;
  16070. this._occlusionInternalRetryCounter = 0;
  16071. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  16072. // if strict continue the last state of the object.
  16073. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  16074. }
  16075. else {
  16076. return;
  16077. }
  16078. }
  16079. }
  16080. var scene = this.getScene();
  16081. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  16082. if (!this._occlusionQuery) {
  16083. this._occlusionQuery = engine.createQuery();
  16084. }
  16085. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  16086. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  16087. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  16088. this._isOcclusionQueryInProgress = true;
  16089. };
  16090. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  16091. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  16092. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  16093. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  16094. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  16095. return AbstractMesh;
  16096. }(BABYLON.TransformNode));
  16097. BABYLON.AbstractMesh = AbstractMesh;
  16098. })(BABYLON || (BABYLON = {}));
  16099. //# sourceMappingURL=babylon.abstractMesh.js.map
  16100. var BABYLON;
  16101. (function (BABYLON) {
  16102. var Light = /** @class */ (function (_super) {
  16103. __extends(Light, _super);
  16104. /**
  16105. * Creates a Light object in the scene.
  16106. * Documentation : http://doc.babylonjs.com/tutorials/lights
  16107. */
  16108. function Light(name, scene) {
  16109. var _this = _super.call(this, name, scene) || this;
  16110. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  16111. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  16112. _this.intensity = 1.0;
  16113. _this.range = Number.MAX_VALUE;
  16114. /**
  16115. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  16116. * of light.
  16117. */
  16118. _this._photometricScale = 1.0;
  16119. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  16120. _this._radius = 0.00001;
  16121. _this.renderPriority = 0;
  16122. /**
  16123. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  16124. * the current shadow generator.
  16125. */
  16126. _this.shadowEnabled = true;
  16127. _this._excludeWithLayerMask = 0;
  16128. _this._includeOnlyWithLayerMask = 0;
  16129. _this._lightmapMode = 0;
  16130. _this._excludedMeshesIds = new Array();
  16131. _this._includedOnlyMeshesIds = new Array();
  16132. _this.getScene().addLight(_this);
  16133. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  16134. _this._buildUniformLayout();
  16135. _this.includedOnlyMeshes = new Array();
  16136. _this.excludedMeshes = new Array();
  16137. _this._resyncMeshes();
  16138. return _this;
  16139. }
  16140. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  16141. /**
  16142. * If every light affecting the material is in this lightmapMode,
  16143. * material.lightmapTexture adds or multiplies
  16144. * (depends on material.useLightmapAsShadowmap)
  16145. * after every other light calculations.
  16146. */
  16147. get: function () {
  16148. return Light._LIGHTMAP_DEFAULT;
  16149. },
  16150. enumerable: true,
  16151. configurable: true
  16152. });
  16153. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  16154. /**
  16155. * material.lightmapTexture as only diffuse lighting from this light
  16156. * adds pnly specular lighting from this light
  16157. * adds dynamic shadows
  16158. */
  16159. get: function () {
  16160. return Light._LIGHTMAP_SPECULAR;
  16161. },
  16162. enumerable: true,
  16163. configurable: true
  16164. });
  16165. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  16166. /**
  16167. * material.lightmapTexture as only lighting
  16168. * no light calculation from this light
  16169. * only adds dynamic shadows from this light
  16170. */
  16171. get: function () {
  16172. return Light._LIGHTMAP_SHADOWSONLY;
  16173. },
  16174. enumerable: true,
  16175. configurable: true
  16176. });
  16177. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  16178. /**
  16179. * Each light type uses the default quantity according to its type:
  16180. * point/spot lights use luminous intensity
  16181. * directional lights use illuminance
  16182. */
  16183. get: function () {
  16184. return Light._INTENSITYMODE_AUTOMATIC;
  16185. },
  16186. enumerable: true,
  16187. configurable: true
  16188. });
  16189. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  16190. /**
  16191. * lumen (lm)
  16192. */
  16193. get: function () {
  16194. return Light._INTENSITYMODE_LUMINOUSPOWER;
  16195. },
  16196. enumerable: true,
  16197. configurable: true
  16198. });
  16199. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  16200. /**
  16201. * candela (lm/sr)
  16202. */
  16203. get: function () {
  16204. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  16205. },
  16206. enumerable: true,
  16207. configurable: true
  16208. });
  16209. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  16210. /**
  16211. * lux (lm/m^2)
  16212. */
  16213. get: function () {
  16214. return Light._INTENSITYMODE_ILLUMINANCE;
  16215. },
  16216. enumerable: true,
  16217. configurable: true
  16218. });
  16219. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  16220. /**
  16221. * nit (cd/m^2)
  16222. */
  16223. get: function () {
  16224. return Light._INTENSITYMODE_LUMINANCE;
  16225. },
  16226. enumerable: true,
  16227. configurable: true
  16228. });
  16229. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  16230. /**
  16231. * Light type const id of the point light.
  16232. */
  16233. get: function () {
  16234. return Light._LIGHTTYPEID_POINTLIGHT;
  16235. },
  16236. enumerable: true,
  16237. configurable: true
  16238. });
  16239. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  16240. /**
  16241. * Light type const id of the directional light.
  16242. */
  16243. get: function () {
  16244. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  16245. },
  16246. enumerable: true,
  16247. configurable: true
  16248. });
  16249. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  16250. /**
  16251. * Light type const id of the spot light.
  16252. */
  16253. get: function () {
  16254. return Light._LIGHTTYPEID_SPOTLIGHT;
  16255. },
  16256. enumerable: true,
  16257. configurable: true
  16258. });
  16259. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  16260. /**
  16261. * Light type const id of the hemispheric light.
  16262. */
  16263. get: function () {
  16264. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  16265. },
  16266. enumerable: true,
  16267. configurable: true
  16268. });
  16269. Object.defineProperty(Light.prototype, "intensityMode", {
  16270. /**
  16271. * Gets the photometric scale used to interpret the intensity.
  16272. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  16273. */
  16274. get: function () {
  16275. return this._intensityMode;
  16276. },
  16277. /**
  16278. * Sets the photometric scale used to interpret the intensity.
  16279. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  16280. */
  16281. set: function (value) {
  16282. this._intensityMode = value;
  16283. this._computePhotometricScale();
  16284. },
  16285. enumerable: true,
  16286. configurable: true
  16287. });
  16288. ;
  16289. ;
  16290. Object.defineProperty(Light.prototype, "radius", {
  16291. /**
  16292. * Gets the light radius used by PBR Materials to simulate soft area lights.
  16293. */
  16294. get: function () {
  16295. return this._radius;
  16296. },
  16297. /**
  16298. * sets the light radius used by PBR Materials to simulate soft area lights.
  16299. */
  16300. set: function (value) {
  16301. this._radius = value;
  16302. this._computePhotometricScale();
  16303. },
  16304. enumerable: true,
  16305. configurable: true
  16306. });
  16307. ;
  16308. ;
  16309. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  16310. get: function () {
  16311. return this._includedOnlyMeshes;
  16312. },
  16313. set: function (value) {
  16314. this._includedOnlyMeshes = value;
  16315. this._hookArrayForIncludedOnly(value);
  16316. },
  16317. enumerable: true,
  16318. configurable: true
  16319. });
  16320. Object.defineProperty(Light.prototype, "excludedMeshes", {
  16321. get: function () {
  16322. return this._excludedMeshes;
  16323. },
  16324. set: function (value) {
  16325. this._excludedMeshes = value;
  16326. this._hookArrayForExcluded(value);
  16327. },
  16328. enumerable: true,
  16329. configurable: true
  16330. });
  16331. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  16332. get: function () {
  16333. return this._excludeWithLayerMask;
  16334. },
  16335. set: function (value) {
  16336. this._excludeWithLayerMask = value;
  16337. this._resyncMeshes();
  16338. },
  16339. enumerable: true,
  16340. configurable: true
  16341. });
  16342. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  16343. get: function () {
  16344. return this._includeOnlyWithLayerMask;
  16345. },
  16346. set: function (value) {
  16347. this._includeOnlyWithLayerMask = value;
  16348. this._resyncMeshes();
  16349. },
  16350. enumerable: true,
  16351. configurable: true
  16352. });
  16353. Object.defineProperty(Light.prototype, "lightmapMode", {
  16354. get: function () {
  16355. return this._lightmapMode;
  16356. },
  16357. set: function (value) {
  16358. if (this._lightmapMode === value) {
  16359. return;
  16360. }
  16361. this._lightmapMode = value;
  16362. this._markMeshesAsLightDirty();
  16363. },
  16364. enumerable: true,
  16365. configurable: true
  16366. });
  16367. Light.prototype._buildUniformLayout = function () {
  16368. // Overridden
  16369. };
  16370. /**
  16371. * Returns the string "Light".
  16372. */
  16373. Light.prototype.getClassName = function () {
  16374. return "Light";
  16375. };
  16376. /**
  16377. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  16378. */
  16379. Light.prototype.toString = function (fullDetails) {
  16380. var ret = "Name: " + this.name;
  16381. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  16382. if (this.animations) {
  16383. for (var i = 0; i < this.animations.length; i++) {
  16384. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  16385. }
  16386. }
  16387. if (fullDetails) {
  16388. }
  16389. return ret;
  16390. };
  16391. /**
  16392. * Set the enabled state of this node.
  16393. * @param {boolean} value - the new enabled state
  16394. * @see isEnabled
  16395. */
  16396. Light.prototype.setEnabled = function (value) {
  16397. _super.prototype.setEnabled.call(this, value);
  16398. this._resyncMeshes();
  16399. };
  16400. /**
  16401. * Returns the Light associated shadow generator.
  16402. */
  16403. Light.prototype.getShadowGenerator = function () {
  16404. return this._shadowGenerator;
  16405. };
  16406. /**
  16407. * Returns a Vector3, the absolute light position in the World.
  16408. */
  16409. Light.prototype.getAbsolutePosition = function () {
  16410. return BABYLON.Vector3.Zero();
  16411. };
  16412. Light.prototype.transferToEffect = function (effect, lightIndex) {
  16413. };
  16414. Light.prototype._getWorldMatrix = function () {
  16415. return BABYLON.Matrix.Identity();
  16416. };
  16417. /**
  16418. * Boolean : True if the light will affect the passed mesh.
  16419. */
  16420. Light.prototype.canAffectMesh = function (mesh) {
  16421. if (!mesh) {
  16422. return true;
  16423. }
  16424. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  16425. return false;
  16426. }
  16427. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  16428. return false;
  16429. }
  16430. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  16431. return false;
  16432. }
  16433. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  16434. return false;
  16435. }
  16436. return true;
  16437. };
  16438. /**
  16439. * Returns the light World matrix.
  16440. */
  16441. Light.prototype.getWorldMatrix = function () {
  16442. this._currentRenderId = this.getScene().getRenderId();
  16443. var worldMatrix = this._getWorldMatrix();
  16444. if (this.parent && this.parent.getWorldMatrix) {
  16445. if (!this._parentedWorldMatrix) {
  16446. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  16447. }
  16448. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  16449. this._markSyncedWithParent();
  16450. return this._parentedWorldMatrix;
  16451. }
  16452. return worldMatrix;
  16453. };
  16454. /**
  16455. * Sort function to order lights for rendering.
  16456. * @param a First Light object to compare to second.
  16457. * @param b Second Light object to compare first.
  16458. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  16459. */
  16460. Light.compareLightsPriority = function (a, b) {
  16461. //shadow-casting lights have priority over non-shadow-casting lights
  16462. //the renderPrioirty is a secondary sort criterion
  16463. if (a.shadowEnabled !== b.shadowEnabled) {
  16464. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  16465. }
  16466. return b.renderPriority - a.renderPriority;
  16467. };
  16468. /**
  16469. * Disposes the light.
  16470. */
  16471. Light.prototype.dispose = function () {
  16472. if (this._shadowGenerator) {
  16473. this._shadowGenerator.dispose();
  16474. this._shadowGenerator = null;
  16475. }
  16476. // Animations
  16477. this.getScene().stopAnimation(this);
  16478. // Remove from meshes
  16479. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  16480. var mesh = _a[_i];
  16481. mesh._removeLightSource(this);
  16482. }
  16483. this._uniformBuffer.dispose();
  16484. // Remove from scene
  16485. this.getScene().removeLight(this);
  16486. _super.prototype.dispose.call(this);
  16487. };
  16488. /**
  16489. * Returns the light type ID (integer).
  16490. */
  16491. Light.prototype.getTypeID = function () {
  16492. return 0;
  16493. };
  16494. /**
  16495. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  16496. */
  16497. Light.prototype.getScaledIntensity = function () {
  16498. return this._photometricScale * this.intensity;
  16499. };
  16500. /**
  16501. * Returns a new Light object, named "name", from the current one.
  16502. */
  16503. Light.prototype.clone = function (name) {
  16504. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  16505. if (!constructor) {
  16506. return null;
  16507. }
  16508. return BABYLON.SerializationHelper.Clone(constructor, this);
  16509. };
  16510. /**
  16511. * Serializes the current light into a Serialization object.
  16512. * Returns the serialized object.
  16513. */
  16514. Light.prototype.serialize = function () {
  16515. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  16516. // Type
  16517. serializationObject.type = this.getTypeID();
  16518. // Parent
  16519. if (this.parent) {
  16520. serializationObject.parentId = this.parent.id;
  16521. }
  16522. // Inclusion / exclusions
  16523. if (this.excludedMeshes.length > 0) {
  16524. serializationObject.excludedMeshesIds = [];
  16525. this.excludedMeshes.forEach(function (mesh) {
  16526. serializationObject.excludedMeshesIds.push(mesh.id);
  16527. });
  16528. }
  16529. if (this.includedOnlyMeshes.length > 0) {
  16530. serializationObject.includedOnlyMeshesIds = [];
  16531. this.includedOnlyMeshes.forEach(function (mesh) {
  16532. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  16533. });
  16534. }
  16535. // Animations
  16536. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  16537. serializationObject.ranges = this.serializeAnimationRanges();
  16538. return serializationObject;
  16539. };
  16540. /**
  16541. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  16542. * This new light is named "name" and added to the passed scene.
  16543. */
  16544. Light.GetConstructorFromName = function (type, name, scene) {
  16545. switch (type) {
  16546. case 0:
  16547. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  16548. case 1:
  16549. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  16550. case 2:
  16551. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  16552. case 3:
  16553. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  16554. }
  16555. return null;
  16556. };
  16557. /**
  16558. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  16559. */
  16560. Light.Parse = function (parsedLight, scene) {
  16561. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  16562. if (!constructor) {
  16563. return null;
  16564. }
  16565. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  16566. // Inclusion / exclusions
  16567. if (parsedLight.excludedMeshesIds) {
  16568. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  16569. }
  16570. if (parsedLight.includedOnlyMeshesIds) {
  16571. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  16572. }
  16573. // Parent
  16574. if (parsedLight.parentId) {
  16575. light._waitingParentId = parsedLight.parentId;
  16576. }
  16577. // Animations
  16578. if (parsedLight.animations) {
  16579. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  16580. var parsedAnimation = parsedLight.animations[animationIndex];
  16581. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  16582. }
  16583. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  16584. }
  16585. if (parsedLight.autoAnimate) {
  16586. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  16587. }
  16588. return light;
  16589. };
  16590. Light.prototype._hookArrayForExcluded = function (array) {
  16591. var _this = this;
  16592. var oldPush = array.push;
  16593. array.push = function () {
  16594. var items = [];
  16595. for (var _i = 0; _i < arguments.length; _i++) {
  16596. items[_i] = arguments[_i];
  16597. }
  16598. var result = oldPush.apply(array, items);
  16599. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  16600. var item = items_1[_a];
  16601. item._resyncLighSource(_this);
  16602. }
  16603. return result;
  16604. };
  16605. var oldSplice = array.splice;
  16606. array.splice = function (index, deleteCount) {
  16607. var deleted = oldSplice.apply(array, [index, deleteCount]);
  16608. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  16609. var item = deleted_1[_i];
  16610. item._resyncLighSource(_this);
  16611. }
  16612. return deleted;
  16613. };
  16614. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  16615. var item = array_1[_i];
  16616. item._resyncLighSource(this);
  16617. }
  16618. };
  16619. Light.prototype._hookArrayForIncludedOnly = function (array) {
  16620. var _this = this;
  16621. var oldPush = array.push;
  16622. array.push = function () {
  16623. var items = [];
  16624. for (var _i = 0; _i < arguments.length; _i++) {
  16625. items[_i] = arguments[_i];
  16626. }
  16627. var result = oldPush.apply(array, items);
  16628. _this._resyncMeshes();
  16629. return result;
  16630. };
  16631. var oldSplice = array.splice;
  16632. array.splice = function (index, deleteCount) {
  16633. var deleted = oldSplice.apply(array, [index, deleteCount]);
  16634. _this._resyncMeshes();
  16635. return deleted;
  16636. };
  16637. this._resyncMeshes();
  16638. };
  16639. Light.prototype._resyncMeshes = function () {
  16640. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  16641. var mesh = _a[_i];
  16642. mesh._resyncLighSource(this);
  16643. }
  16644. };
  16645. Light.prototype._markMeshesAsLightDirty = function () {
  16646. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  16647. var mesh = _a[_i];
  16648. if (mesh._lightSources.indexOf(this) !== -1) {
  16649. mesh._markSubMeshesAsLightDirty();
  16650. }
  16651. }
  16652. };
  16653. /**
  16654. * Recomputes the cached photometric scale if needed.
  16655. */
  16656. Light.prototype._computePhotometricScale = function () {
  16657. this._photometricScale = this._getPhotometricScale();
  16658. this.getScene().resetCachedMaterial();
  16659. };
  16660. /**
  16661. * Returns the Photometric Scale according to the light type and intensity mode.
  16662. */
  16663. Light.prototype._getPhotometricScale = function () {
  16664. var photometricScale = 0.0;
  16665. var lightTypeID = this.getTypeID();
  16666. //get photometric mode
  16667. var photometricMode = this.intensityMode;
  16668. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  16669. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  16670. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  16671. }
  16672. else {
  16673. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  16674. }
  16675. }
  16676. //compute photometric scale
  16677. switch (lightTypeID) {
  16678. case Light.LIGHTTYPEID_POINTLIGHT:
  16679. case Light.LIGHTTYPEID_SPOTLIGHT:
  16680. switch (photometricMode) {
  16681. case Light.INTENSITYMODE_LUMINOUSPOWER:
  16682. photometricScale = 1.0 / (4.0 * Math.PI);
  16683. break;
  16684. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  16685. photometricScale = 1.0;
  16686. break;
  16687. case Light.INTENSITYMODE_LUMINANCE:
  16688. photometricScale = this.radius * this.radius;
  16689. break;
  16690. }
  16691. break;
  16692. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  16693. switch (photometricMode) {
  16694. case Light.INTENSITYMODE_ILLUMINANCE:
  16695. photometricScale = 1.0;
  16696. break;
  16697. case Light.INTENSITYMODE_LUMINANCE:
  16698. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  16699. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  16700. var apexAngleRadians = this.radius;
  16701. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  16702. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  16703. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  16704. photometricScale = solidAngle;
  16705. break;
  16706. }
  16707. break;
  16708. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  16709. // No fall off in hemisperic light.
  16710. photometricScale = 1.0;
  16711. break;
  16712. }
  16713. return photometricScale;
  16714. };
  16715. Light.prototype._reorderLightsInScene = function () {
  16716. var scene = this.getScene();
  16717. if (this._renderPriority != 0) {
  16718. scene.requireLightSorting = true;
  16719. }
  16720. this.getScene().sortLightsByPriority();
  16721. };
  16722. //lightmapMode Consts
  16723. Light._LIGHTMAP_DEFAULT = 0;
  16724. Light._LIGHTMAP_SPECULAR = 1;
  16725. Light._LIGHTMAP_SHADOWSONLY = 2;
  16726. // Intensity Mode Consts
  16727. Light._INTENSITYMODE_AUTOMATIC = 0;
  16728. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  16729. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  16730. Light._INTENSITYMODE_ILLUMINANCE = 3;
  16731. Light._INTENSITYMODE_LUMINANCE = 4;
  16732. // Light types ids const.
  16733. Light._LIGHTTYPEID_POINTLIGHT = 0;
  16734. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  16735. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  16736. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  16737. __decorate([
  16738. BABYLON.serializeAsColor3()
  16739. ], Light.prototype, "diffuse", void 0);
  16740. __decorate([
  16741. BABYLON.serializeAsColor3()
  16742. ], Light.prototype, "specular", void 0);
  16743. __decorate([
  16744. BABYLON.serialize()
  16745. ], Light.prototype, "intensity", void 0);
  16746. __decorate([
  16747. BABYLON.serialize()
  16748. ], Light.prototype, "range", void 0);
  16749. __decorate([
  16750. BABYLON.serialize()
  16751. ], Light.prototype, "intensityMode", null);
  16752. __decorate([
  16753. BABYLON.serialize()
  16754. ], Light.prototype, "radius", null);
  16755. __decorate([
  16756. BABYLON.serialize()
  16757. ], Light.prototype, "_renderPriority", void 0);
  16758. __decorate([
  16759. BABYLON.expandToProperty("_reorderLightsInScene")
  16760. ], Light.prototype, "renderPriority", void 0);
  16761. __decorate([
  16762. BABYLON.serialize()
  16763. ], Light.prototype, "shadowEnabled", void 0);
  16764. __decorate([
  16765. BABYLON.serialize("excludeWithLayerMask")
  16766. ], Light.prototype, "_excludeWithLayerMask", void 0);
  16767. __decorate([
  16768. BABYLON.serialize("includeOnlyWithLayerMask")
  16769. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  16770. __decorate([
  16771. BABYLON.serialize("lightmapMode")
  16772. ], Light.prototype, "_lightmapMode", void 0);
  16773. return Light;
  16774. }(BABYLON.Node));
  16775. BABYLON.Light = Light;
  16776. })(BABYLON || (BABYLON = {}));
  16777. //# sourceMappingURL=babylon.light.js.map
  16778. var BABYLON;
  16779. (function (BABYLON) {
  16780. var Camera = /** @class */ (function (_super) {
  16781. __extends(Camera, _super);
  16782. function Camera(name, position, scene) {
  16783. var _this = _super.call(this, name, scene) || this;
  16784. _this.upVector = BABYLON.Vector3.Up();
  16785. _this.orthoLeft = null;
  16786. _this.orthoRight = null;
  16787. _this.orthoBottom = null;
  16788. _this.orthoTop = null;
  16789. _this.fov = 0.8;
  16790. _this.minZ = 1;
  16791. _this.maxZ = 10000.0;
  16792. _this.inertia = 0.9;
  16793. _this.mode = Camera.PERSPECTIVE_CAMERA;
  16794. _this.isIntermediate = false;
  16795. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  16796. _this.layerMask = 0x0FFFFFFF;
  16797. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  16798. // Camera rig members
  16799. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  16800. _this._rigCameras = new Array();
  16801. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  16802. _this._skipRendering = false;
  16803. _this.customRenderTargets = new Array();
  16804. // Observables
  16805. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  16806. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  16807. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  16808. _this.onRestoreStateObservable = new BABYLON.Observable();
  16809. // Cache
  16810. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  16811. _this._projectionMatrix = new BABYLON.Matrix();
  16812. _this._doNotComputeProjectionMatrix = false;
  16813. _this._postProcesses = new Array();
  16814. _this._transformMatrix = BABYLON.Matrix.Zero();
  16815. _this._activeMeshes = new BABYLON.SmartArray(256);
  16816. _this._globalPosition = BABYLON.Vector3.Zero();
  16817. _this._refreshFrustumPlanes = true;
  16818. _this.getScene().addCamera(_this);
  16819. if (!_this.getScene().activeCamera) {
  16820. _this.getScene().activeCamera = _this;
  16821. }
  16822. _this.position = position;
  16823. return _this;
  16824. }
  16825. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  16826. get: function () {
  16827. return Camera._PERSPECTIVE_CAMERA;
  16828. },
  16829. enumerable: true,
  16830. configurable: true
  16831. });
  16832. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  16833. get: function () {
  16834. return Camera._ORTHOGRAPHIC_CAMERA;
  16835. },
  16836. enumerable: true,
  16837. configurable: true
  16838. });
  16839. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  16840. get: function () {
  16841. return Camera._FOVMODE_VERTICAL_FIXED;
  16842. },
  16843. enumerable: true,
  16844. configurable: true
  16845. });
  16846. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  16847. get: function () {
  16848. return Camera._FOVMODE_HORIZONTAL_FIXED;
  16849. },
  16850. enumerable: true,
  16851. configurable: true
  16852. });
  16853. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  16854. get: function () {
  16855. return Camera._RIG_MODE_NONE;
  16856. },
  16857. enumerable: true,
  16858. configurable: true
  16859. });
  16860. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  16861. get: function () {
  16862. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  16863. },
  16864. enumerable: true,
  16865. configurable: true
  16866. });
  16867. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  16868. get: function () {
  16869. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  16870. },
  16871. enumerable: true,
  16872. configurable: true
  16873. });
  16874. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  16875. get: function () {
  16876. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  16877. },
  16878. enumerable: true,
  16879. configurable: true
  16880. });
  16881. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  16882. get: function () {
  16883. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  16884. },
  16885. enumerable: true,
  16886. configurable: true
  16887. });
  16888. Object.defineProperty(Camera, "RIG_MODE_VR", {
  16889. get: function () {
  16890. return Camera._RIG_MODE_VR;
  16891. },
  16892. enumerable: true,
  16893. configurable: true
  16894. });
  16895. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  16896. get: function () {
  16897. return Camera._RIG_MODE_WEBVR;
  16898. },
  16899. enumerable: true,
  16900. configurable: true
  16901. });
  16902. /**
  16903. * Store current camera state (fov, position, etc..)
  16904. */
  16905. Camera.prototype.storeState = function () {
  16906. this._stateStored = true;
  16907. this._storedFov = this.fov;
  16908. return this;
  16909. };
  16910. /**
  16911. * Restores the camera state values if it has been stored. You must call storeState() first
  16912. */
  16913. Camera.prototype._restoreStateValues = function () {
  16914. if (!this._stateStored) {
  16915. return false;
  16916. }
  16917. this.fov = this._storedFov;
  16918. return true;
  16919. };
  16920. /**
  16921. * Restored camera state. You must call storeState() first
  16922. */
  16923. Camera.prototype.restoreState = function () {
  16924. if (this._restoreStateValues()) {
  16925. this.onRestoreStateObservable.notifyObservers(this);
  16926. return true;
  16927. }
  16928. return false;
  16929. };
  16930. Camera.prototype.getClassName = function () {
  16931. return "Camera";
  16932. };
  16933. /**
  16934. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  16935. */
  16936. Camera.prototype.toString = function (fullDetails) {
  16937. var ret = "Name: " + this.name;
  16938. ret += ", type: " + this.getClassName();
  16939. if (this.animations) {
  16940. for (var i = 0; i < this.animations.length; i++) {
  16941. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  16942. }
  16943. }
  16944. if (fullDetails) {
  16945. }
  16946. return ret;
  16947. };
  16948. Object.defineProperty(Camera.prototype, "globalPosition", {
  16949. get: function () {
  16950. return this._globalPosition;
  16951. },
  16952. enumerable: true,
  16953. configurable: true
  16954. });
  16955. Camera.prototype.getActiveMeshes = function () {
  16956. return this._activeMeshes;
  16957. };
  16958. Camera.prototype.isActiveMesh = function (mesh) {
  16959. return (this._activeMeshes.indexOf(mesh) !== -1);
  16960. };
  16961. //Cache
  16962. Camera.prototype._initCache = function () {
  16963. _super.prototype._initCache.call(this);
  16964. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  16965. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  16966. this._cache.mode = undefined;
  16967. this._cache.minZ = undefined;
  16968. this._cache.maxZ = undefined;
  16969. this._cache.fov = undefined;
  16970. this._cache.fovMode = undefined;
  16971. this._cache.aspectRatio = undefined;
  16972. this._cache.orthoLeft = undefined;
  16973. this._cache.orthoRight = undefined;
  16974. this._cache.orthoBottom = undefined;
  16975. this._cache.orthoTop = undefined;
  16976. this._cache.renderWidth = undefined;
  16977. this._cache.renderHeight = undefined;
  16978. };
  16979. Camera.prototype._updateCache = function (ignoreParentClass) {
  16980. if (!ignoreParentClass) {
  16981. _super.prototype._updateCache.call(this);
  16982. }
  16983. this._cache.position.copyFrom(this.position);
  16984. this._cache.upVector.copyFrom(this.upVector);
  16985. };
  16986. // Synchronized
  16987. Camera.prototype._isSynchronized = function () {
  16988. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  16989. };
  16990. Camera.prototype._isSynchronizedViewMatrix = function () {
  16991. if (!_super.prototype._isSynchronized.call(this))
  16992. return false;
  16993. return this._cache.position.equals(this.position)
  16994. && this._cache.upVector.equals(this.upVector)
  16995. && this.isSynchronizedWithParent();
  16996. };
  16997. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  16998. var check = this._cache.mode === this.mode
  16999. && this._cache.minZ === this.minZ
  17000. && this._cache.maxZ === this.maxZ;
  17001. if (!check) {
  17002. return false;
  17003. }
  17004. var engine = this.getEngine();
  17005. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  17006. check = this._cache.fov === this.fov
  17007. && this._cache.fovMode === this.fovMode
  17008. && this._cache.aspectRatio === engine.getAspectRatio(this);
  17009. }
  17010. else {
  17011. check = this._cache.orthoLeft === this.orthoLeft
  17012. && this._cache.orthoRight === this.orthoRight
  17013. && this._cache.orthoBottom === this.orthoBottom
  17014. && this._cache.orthoTop === this.orthoTop
  17015. && this._cache.renderWidth === engine.getRenderWidth()
  17016. && this._cache.renderHeight === engine.getRenderHeight();
  17017. }
  17018. return check;
  17019. };
  17020. // Controls
  17021. Camera.prototype.attachControl = function (element, noPreventDefault) {
  17022. };
  17023. Camera.prototype.detachControl = function (element) {
  17024. };
  17025. Camera.prototype.update = function () {
  17026. this._checkInputs();
  17027. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  17028. this._updateRigCameras();
  17029. }
  17030. };
  17031. Camera.prototype._checkInputs = function () {
  17032. this.onAfterCheckInputsObservable.notifyObservers(this);
  17033. };
  17034. Object.defineProperty(Camera.prototype, "rigCameras", {
  17035. get: function () {
  17036. return this._rigCameras;
  17037. },
  17038. enumerable: true,
  17039. configurable: true
  17040. });
  17041. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  17042. get: function () {
  17043. return this._rigPostProcess;
  17044. },
  17045. enumerable: true,
  17046. configurable: true
  17047. });
  17048. Camera.prototype._cascadePostProcessesToRigCams = function () {
  17049. // invalidate framebuffer
  17050. if (this._postProcesses.length > 0) {
  17051. this._postProcesses[0].markTextureDirty();
  17052. }
  17053. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  17054. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  17055. var cam = this._rigCameras[i];
  17056. var rigPostProcess = cam._rigPostProcess;
  17057. // for VR rig, there does not have to be a post process
  17058. if (rigPostProcess) {
  17059. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  17060. if (isPass) {
  17061. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  17062. cam.isIntermediate = this._postProcesses.length === 0;
  17063. }
  17064. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  17065. rigPostProcess.markTextureDirty();
  17066. }
  17067. else {
  17068. cam._postProcesses = this._postProcesses.slice(0);
  17069. }
  17070. }
  17071. };
  17072. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  17073. if (insertAt === void 0) { insertAt = null; }
  17074. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  17075. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  17076. return 0;
  17077. }
  17078. if (insertAt == null || insertAt < 0) {
  17079. this._postProcesses.push(postProcess);
  17080. }
  17081. else {
  17082. this._postProcesses.splice(insertAt, 0, postProcess);
  17083. }
  17084. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  17085. return this._postProcesses.indexOf(postProcess);
  17086. };
  17087. Camera.prototype.detachPostProcess = function (postProcess) {
  17088. var idx = this._postProcesses.indexOf(postProcess);
  17089. if (idx !== -1) {
  17090. this._postProcesses.splice(idx, 1);
  17091. }
  17092. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  17093. };
  17094. Camera.prototype.getWorldMatrix = function () {
  17095. if (!this._worldMatrix) {
  17096. this._worldMatrix = BABYLON.Matrix.Identity();
  17097. }
  17098. var viewMatrix = this.getViewMatrix();
  17099. viewMatrix.invertToRef(this._worldMatrix);
  17100. return this._worldMatrix;
  17101. };
  17102. Camera.prototype._getViewMatrix = function () {
  17103. return BABYLON.Matrix.Identity();
  17104. };
  17105. Camera.prototype.getViewMatrix = function (force) {
  17106. if (!force && this._isSynchronizedViewMatrix()) {
  17107. return this._computedViewMatrix;
  17108. }
  17109. this.updateCache();
  17110. this._computedViewMatrix = this._getViewMatrix();
  17111. this._currentRenderId = this.getScene().getRenderId();
  17112. this._refreshFrustumPlanes = true;
  17113. if (!this.parent || !this.parent.getWorldMatrix) {
  17114. this._globalPosition.copyFrom(this.position);
  17115. }
  17116. else {
  17117. if (!this._worldMatrix) {
  17118. this._worldMatrix = BABYLON.Matrix.Identity();
  17119. }
  17120. this._computedViewMatrix.invertToRef(this._worldMatrix);
  17121. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  17122. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  17123. this._computedViewMatrix.invert();
  17124. this._markSyncedWithParent();
  17125. }
  17126. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  17127. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  17128. }
  17129. this.onViewMatrixChangedObservable.notifyObservers(this);
  17130. return this._computedViewMatrix;
  17131. };
  17132. Camera.prototype.freezeProjectionMatrix = function (projection) {
  17133. this._doNotComputeProjectionMatrix = true;
  17134. if (projection !== undefined) {
  17135. this._projectionMatrix = projection;
  17136. }
  17137. };
  17138. ;
  17139. Camera.prototype.unfreezeProjectionMatrix = function () {
  17140. this._doNotComputeProjectionMatrix = false;
  17141. };
  17142. ;
  17143. Camera.prototype.getProjectionMatrix = function (force) {
  17144. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  17145. return this._projectionMatrix;
  17146. }
  17147. // Cache
  17148. this._cache.mode = this.mode;
  17149. this._cache.minZ = this.minZ;
  17150. this._cache.maxZ = this.maxZ;
  17151. // Matrix
  17152. this._refreshFrustumPlanes = true;
  17153. var engine = this.getEngine();
  17154. var scene = this.getScene();
  17155. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  17156. this._cache.fov = this.fov;
  17157. this._cache.fovMode = this.fovMode;
  17158. this._cache.aspectRatio = engine.getAspectRatio(this);
  17159. if (this.minZ <= 0) {
  17160. this.minZ = 0.1;
  17161. }
  17162. if (scene.useRightHandedSystem) {
  17163. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  17164. }
  17165. else {
  17166. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  17167. }
  17168. }
  17169. else {
  17170. var halfWidth = engine.getRenderWidth() / 2.0;
  17171. var halfHeight = engine.getRenderHeight() / 2.0;
  17172. if (scene.useRightHandedSystem) {
  17173. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  17174. }
  17175. else {
  17176. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  17177. }
  17178. this._cache.orthoLeft = this.orthoLeft;
  17179. this._cache.orthoRight = this.orthoRight;
  17180. this._cache.orthoBottom = this.orthoBottom;
  17181. this._cache.orthoTop = this.orthoTop;
  17182. this._cache.renderWidth = engine.getRenderWidth();
  17183. this._cache.renderHeight = engine.getRenderHeight();
  17184. }
  17185. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  17186. return this._projectionMatrix;
  17187. };
  17188. Camera.prototype.getTranformationMatrix = function () {
  17189. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  17190. return this._transformMatrix;
  17191. };
  17192. Camera.prototype.updateFrustumPlanes = function () {
  17193. if (!this._refreshFrustumPlanes) {
  17194. return;
  17195. }
  17196. this.getTranformationMatrix();
  17197. if (!this._frustumPlanes) {
  17198. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  17199. }
  17200. else {
  17201. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  17202. }
  17203. this._refreshFrustumPlanes = false;
  17204. };
  17205. Camera.prototype.isInFrustum = function (target) {
  17206. this.updateFrustumPlanes();
  17207. return target.isInFrustum(this._frustumPlanes);
  17208. };
  17209. Camera.prototype.isCompletelyInFrustum = function (target) {
  17210. this.updateFrustumPlanes();
  17211. return target.isCompletelyInFrustum(this._frustumPlanes);
  17212. };
  17213. Camera.prototype.getForwardRay = function (length, transform, origin) {
  17214. if (length === void 0) { length = 100; }
  17215. if (!transform) {
  17216. transform = this.getWorldMatrix();
  17217. }
  17218. if (!origin) {
  17219. origin = this.position;
  17220. }
  17221. var forward = new BABYLON.Vector3(0, 0, 1);
  17222. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  17223. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  17224. return new BABYLON.Ray(origin, direction, length);
  17225. };
  17226. Camera.prototype.dispose = function () {
  17227. // Observables
  17228. this.onViewMatrixChangedObservable.clear();
  17229. this.onProjectionMatrixChangedObservable.clear();
  17230. this.onAfterCheckInputsObservable.clear();
  17231. this.onRestoreStateObservable.clear();
  17232. // Inputs
  17233. if (this.inputs) {
  17234. this.inputs.clear();
  17235. }
  17236. // Animations
  17237. this.getScene().stopAnimation(this);
  17238. // Remove from scene
  17239. this.getScene().removeCamera(this);
  17240. while (this._rigCameras.length > 0) {
  17241. var camera = this._rigCameras.pop();
  17242. if (camera) {
  17243. camera.dispose();
  17244. }
  17245. }
  17246. // Postprocesses
  17247. if (this._rigPostProcess) {
  17248. this._rigPostProcess.dispose(this);
  17249. this._rigPostProcess = null;
  17250. this._postProcesses = [];
  17251. }
  17252. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  17253. this._rigPostProcess = null;
  17254. this._postProcesses = [];
  17255. }
  17256. else {
  17257. var i = this._postProcesses.length;
  17258. while (--i >= 0) {
  17259. this._postProcesses[i].dispose(this);
  17260. }
  17261. }
  17262. // Render targets
  17263. var i = this.customRenderTargets.length;
  17264. while (--i >= 0) {
  17265. this.customRenderTargets[i].dispose();
  17266. }
  17267. this.customRenderTargets = [];
  17268. // Active Meshes
  17269. this._activeMeshes.dispose();
  17270. _super.prototype.dispose.call(this);
  17271. };
  17272. Object.defineProperty(Camera.prototype, "leftCamera", {
  17273. // ---- Camera rigs section ----
  17274. get: function () {
  17275. if (this._rigCameras.length < 1) {
  17276. return null;
  17277. }
  17278. return this._rigCameras[0];
  17279. },
  17280. enumerable: true,
  17281. configurable: true
  17282. });
  17283. Object.defineProperty(Camera.prototype, "rightCamera", {
  17284. get: function () {
  17285. if (this._rigCameras.length < 2) {
  17286. return null;
  17287. }
  17288. return this._rigCameras[1];
  17289. },
  17290. enumerable: true,
  17291. configurable: true
  17292. });
  17293. Camera.prototype.getLeftTarget = function () {
  17294. if (this._rigCameras.length < 1) {
  17295. return null;
  17296. }
  17297. return this._rigCameras[0].getTarget();
  17298. };
  17299. Camera.prototype.getRightTarget = function () {
  17300. if (this._rigCameras.length < 2) {
  17301. return null;
  17302. }
  17303. return this._rigCameras[1].getTarget();
  17304. };
  17305. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  17306. if (this.cameraRigMode === mode) {
  17307. return;
  17308. }
  17309. while (this._rigCameras.length > 0) {
  17310. var camera = this._rigCameras.pop();
  17311. if (camera) {
  17312. camera.dispose();
  17313. }
  17314. }
  17315. this.cameraRigMode = mode;
  17316. this._cameraRigParams = {};
  17317. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  17318. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  17319. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  17320. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  17321. // create the rig cameras, unless none
  17322. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  17323. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  17324. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  17325. if (leftCamera && rightCamera) {
  17326. this._rigCameras.push(leftCamera);
  17327. this._rigCameras.push(rightCamera);
  17328. }
  17329. }
  17330. switch (this.cameraRigMode) {
  17331. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  17332. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  17333. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  17334. break;
  17335. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  17336. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  17337. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  17338. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  17339. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  17340. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  17341. break;
  17342. case Camera.RIG_MODE_VR:
  17343. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  17344. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  17345. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  17346. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  17347. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  17348. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  17349. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  17350. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  17351. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  17352. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  17353. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  17354. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  17355. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  17356. if (metrics.compensateDistortion) {
  17357. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  17358. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  17359. }
  17360. break;
  17361. case Camera.RIG_MODE_WEBVR:
  17362. if (rigParams.vrDisplay) {
  17363. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  17364. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  17365. //Left eye
  17366. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  17367. this._rigCameras[0].setCameraRigParameter("left", true);
  17368. //leaving this for future reference
  17369. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  17370. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  17371. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  17372. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  17373. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  17374. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  17375. this._rigCameras[0].parent = this;
  17376. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  17377. //Right eye
  17378. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  17379. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  17380. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  17381. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  17382. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  17383. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  17384. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  17385. this._rigCameras[1].parent = this;
  17386. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  17387. if (Camera.UseAlternateWebVRRendering) {
  17388. this._rigCameras[1]._skipRendering = true;
  17389. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  17390. }
  17391. }
  17392. break;
  17393. }
  17394. this._cascadePostProcessesToRigCams();
  17395. this.update();
  17396. };
  17397. Camera.prototype._getVRProjectionMatrix = function () {
  17398. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  17399. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  17400. return this._projectionMatrix;
  17401. };
  17402. Camera.prototype._updateCameraRotationMatrix = function () {
  17403. //Here for WebVR
  17404. };
  17405. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  17406. //Here for WebVR
  17407. };
  17408. /**
  17409. * This function MUST be overwritten by the different WebVR cameras available.
  17410. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  17411. */
  17412. Camera.prototype._getWebVRProjectionMatrix = function () {
  17413. return BABYLON.Matrix.Identity();
  17414. };
  17415. /**
  17416. * This function MUST be overwritten by the different WebVR cameras available.
  17417. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  17418. */
  17419. Camera.prototype._getWebVRViewMatrix = function () {
  17420. return BABYLON.Matrix.Identity();
  17421. };
  17422. Camera.prototype.setCameraRigParameter = function (name, value) {
  17423. if (!this._cameraRigParams) {
  17424. this._cameraRigParams = {};
  17425. }
  17426. this._cameraRigParams[name] = value;
  17427. //provisionnally:
  17428. if (name === "interaxialDistance") {
  17429. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  17430. }
  17431. };
  17432. /**
  17433. * needs to be overridden by children so sub has required properties to be copied
  17434. */
  17435. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  17436. return null;
  17437. };
  17438. /**
  17439. * May need to be overridden by children
  17440. */
  17441. Camera.prototype._updateRigCameras = function () {
  17442. for (var i = 0; i < this._rigCameras.length; i++) {
  17443. this._rigCameras[i].minZ = this.minZ;
  17444. this._rigCameras[i].maxZ = this.maxZ;
  17445. this._rigCameras[i].fov = this.fov;
  17446. }
  17447. // only update viewport when ANAGLYPH
  17448. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  17449. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  17450. }
  17451. };
  17452. Camera.prototype._setupInputs = function () {
  17453. };
  17454. Camera.prototype.serialize = function () {
  17455. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  17456. // Type
  17457. serializationObject.type = this.getClassName();
  17458. // Parent
  17459. if (this.parent) {
  17460. serializationObject.parentId = this.parent.id;
  17461. }
  17462. if (this.inputs) {
  17463. this.inputs.serialize(serializationObject);
  17464. }
  17465. // Animations
  17466. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  17467. serializationObject.ranges = this.serializeAnimationRanges();
  17468. return serializationObject;
  17469. };
  17470. Camera.prototype.clone = function (name) {
  17471. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  17472. };
  17473. Camera.prototype.getDirection = function (localAxis) {
  17474. var result = BABYLON.Vector3.Zero();
  17475. this.getDirectionToRef(localAxis, result);
  17476. return result;
  17477. };
  17478. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  17479. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  17480. };
  17481. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  17482. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  17483. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  17484. switch (type) {
  17485. case "ArcRotateCamera":
  17486. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  17487. case "DeviceOrientationCamera":
  17488. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  17489. case "FollowCamera":
  17490. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  17491. case "ArcFollowCamera":
  17492. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  17493. case "GamepadCamera":
  17494. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  17495. case "TouchCamera":
  17496. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  17497. case "VirtualJoysticksCamera":
  17498. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  17499. case "WebVRFreeCamera":
  17500. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  17501. case "WebVRGamepadCamera":
  17502. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  17503. case "VRDeviceOrientationFreeCamera":
  17504. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  17505. case "VRDeviceOrientationGamepadCamera":
  17506. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  17507. case "AnaglyphArcRotateCamera":
  17508. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  17509. case "AnaglyphFreeCamera":
  17510. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  17511. case "AnaglyphGamepadCamera":
  17512. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  17513. case "AnaglyphUniversalCamera":
  17514. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  17515. case "StereoscopicArcRotateCamera":
  17516. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  17517. case "StereoscopicFreeCamera":
  17518. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  17519. case "StereoscopicGamepadCamera":
  17520. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  17521. case "StereoscopicUniversalCamera":
  17522. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  17523. case "FreeCamera":// Forcing Universal here
  17524. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  17525. default:// Universal Camera is the default value
  17526. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  17527. }
  17528. };
  17529. Camera.prototype.computeWorldMatrix = function () {
  17530. return this.getWorldMatrix();
  17531. };
  17532. Camera.Parse = function (parsedCamera, scene) {
  17533. var type = parsedCamera.type;
  17534. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  17535. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  17536. // Parent
  17537. if (parsedCamera.parentId) {
  17538. camera._waitingParentId = parsedCamera.parentId;
  17539. }
  17540. //If camera has an input manager, let it parse inputs settings
  17541. if (camera.inputs) {
  17542. camera.inputs.parse(parsedCamera);
  17543. camera._setupInputs();
  17544. }
  17545. if (camera.setPosition) {
  17546. camera.position.copyFromFloats(0, 0, 0);
  17547. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  17548. }
  17549. // Target
  17550. if (parsedCamera.target) {
  17551. if (camera.setTarget) {
  17552. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  17553. }
  17554. }
  17555. // Apply 3d rig, when found
  17556. if (parsedCamera.cameraRigMode) {
  17557. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  17558. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  17559. }
  17560. // Animations
  17561. if (parsedCamera.animations) {
  17562. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  17563. var parsedAnimation = parsedCamera.animations[animationIndex];
  17564. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  17565. }
  17566. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  17567. }
  17568. if (parsedCamera.autoAnimate) {
  17569. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  17570. }
  17571. return camera;
  17572. };
  17573. // Statics
  17574. Camera._PERSPECTIVE_CAMERA = 0;
  17575. Camera._ORTHOGRAPHIC_CAMERA = 1;
  17576. Camera._FOVMODE_VERTICAL_FIXED = 0;
  17577. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  17578. Camera._RIG_MODE_NONE = 0;
  17579. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  17580. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  17581. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  17582. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  17583. Camera._RIG_MODE_VR = 20;
  17584. Camera._RIG_MODE_WEBVR = 21;
  17585. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  17586. Camera.UseAlternateWebVRRendering = false;
  17587. __decorate([
  17588. BABYLON.serializeAsVector3()
  17589. ], Camera.prototype, "position", void 0);
  17590. __decorate([
  17591. BABYLON.serializeAsVector3()
  17592. ], Camera.prototype, "upVector", void 0);
  17593. __decorate([
  17594. BABYLON.serialize()
  17595. ], Camera.prototype, "orthoLeft", void 0);
  17596. __decorate([
  17597. BABYLON.serialize()
  17598. ], Camera.prototype, "orthoRight", void 0);
  17599. __decorate([
  17600. BABYLON.serialize()
  17601. ], Camera.prototype, "orthoBottom", void 0);
  17602. __decorate([
  17603. BABYLON.serialize()
  17604. ], Camera.prototype, "orthoTop", void 0);
  17605. __decorate([
  17606. BABYLON.serialize()
  17607. ], Camera.prototype, "fov", void 0);
  17608. __decorate([
  17609. BABYLON.serialize()
  17610. ], Camera.prototype, "minZ", void 0);
  17611. __decorate([
  17612. BABYLON.serialize()
  17613. ], Camera.prototype, "maxZ", void 0);
  17614. __decorate([
  17615. BABYLON.serialize()
  17616. ], Camera.prototype, "inertia", void 0);
  17617. __decorate([
  17618. BABYLON.serialize()
  17619. ], Camera.prototype, "mode", void 0);
  17620. __decorate([
  17621. BABYLON.serialize()
  17622. ], Camera.prototype, "layerMask", void 0);
  17623. __decorate([
  17624. BABYLON.serialize()
  17625. ], Camera.prototype, "fovMode", void 0);
  17626. __decorate([
  17627. BABYLON.serialize()
  17628. ], Camera.prototype, "cameraRigMode", void 0);
  17629. __decorate([
  17630. BABYLON.serialize()
  17631. ], Camera.prototype, "interaxialDistance", void 0);
  17632. __decorate([
  17633. BABYLON.serialize()
  17634. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  17635. return Camera;
  17636. }(BABYLON.Node));
  17637. BABYLON.Camera = Camera;
  17638. })(BABYLON || (BABYLON = {}));
  17639. //# sourceMappingURL=babylon.camera.js.map
  17640. var BABYLON;
  17641. (function (BABYLON) {
  17642. var RenderingManager = /** @class */ (function () {
  17643. function RenderingManager(scene) {
  17644. this._renderingGroups = new Array();
  17645. this._autoClearDepthStencil = {};
  17646. this._customOpaqueSortCompareFn = {};
  17647. this._customAlphaTestSortCompareFn = {};
  17648. this._customTransparentSortCompareFn = {};
  17649. this._renderinGroupInfo = null;
  17650. this._scene = scene;
  17651. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  17652. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  17653. }
  17654. }
  17655. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  17656. if (depth === void 0) { depth = true; }
  17657. if (stencil === void 0) { stencil = true; }
  17658. if (this._depthStencilBufferAlreadyCleaned) {
  17659. return;
  17660. }
  17661. this._scene.getEngine().clear(null, false, depth, stencil);
  17662. this._depthStencilBufferAlreadyCleaned = true;
  17663. };
  17664. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  17665. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  17666. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  17667. var info = null;
  17668. if (observable) {
  17669. if (!this._renderinGroupInfo) {
  17670. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  17671. }
  17672. info = this._renderinGroupInfo;
  17673. info.scene = this._scene;
  17674. info.camera = this._scene.activeCamera;
  17675. }
  17676. // Dispatch sprites
  17677. if (renderSprites) {
  17678. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  17679. var manager = this._scene.spriteManagers[index];
  17680. this.dispatchSprites(manager);
  17681. }
  17682. }
  17683. // Render
  17684. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  17685. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  17686. var renderingGroup = this._renderingGroups[index];
  17687. if (!renderingGroup && !observable)
  17688. continue;
  17689. var renderingGroupMask = 0;
  17690. // Fire PRECLEAR stage
  17691. if (observable && info) {
  17692. renderingGroupMask = Math.pow(2, index);
  17693. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  17694. info.renderingGroupId = index;
  17695. observable.notifyObservers(info, renderingGroupMask);
  17696. }
  17697. // Clear depth/stencil if needed
  17698. if (RenderingManager.AUTOCLEAR) {
  17699. var autoClear = this._autoClearDepthStencil[index];
  17700. if (autoClear && autoClear.autoClear) {
  17701. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  17702. }
  17703. }
  17704. if (observable && info) {
  17705. // Fire PREOPAQUE stage
  17706. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  17707. observable.notifyObservers(info, renderingGroupMask);
  17708. // Fire PRETRANSPARENT stage
  17709. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  17710. observable.notifyObservers(info, renderingGroupMask);
  17711. }
  17712. if (renderingGroup)
  17713. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  17714. // Fire POSTTRANSPARENT stage
  17715. if (observable && info) {
  17716. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  17717. observable.notifyObservers(info, renderingGroupMask);
  17718. }
  17719. }
  17720. };
  17721. RenderingManager.prototype.reset = function () {
  17722. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  17723. var renderingGroup = this._renderingGroups[index];
  17724. if (renderingGroup) {
  17725. renderingGroup.prepare();
  17726. }
  17727. }
  17728. };
  17729. RenderingManager.prototype.dispose = function () {
  17730. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  17731. var renderingGroup = this._renderingGroups[index];
  17732. if (renderingGroup) {
  17733. renderingGroup.dispose();
  17734. }
  17735. }
  17736. this._renderingGroups.length = 0;
  17737. };
  17738. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  17739. if (this._renderingGroups[renderingGroupId] === undefined) {
  17740. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  17741. }
  17742. };
  17743. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  17744. var renderingGroupId = spriteManager.renderingGroupId || 0;
  17745. this._prepareRenderingGroup(renderingGroupId);
  17746. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  17747. };
  17748. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  17749. var renderingGroupId = particleSystem.renderingGroupId || 0;
  17750. this._prepareRenderingGroup(renderingGroupId);
  17751. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  17752. };
  17753. /**
  17754. * @param subMesh The submesh to dispatch
  17755. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  17756. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  17757. */
  17758. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  17759. if (mesh === undefined) {
  17760. mesh = subMesh.getMesh();
  17761. }
  17762. var renderingGroupId = mesh.renderingGroupId || 0;
  17763. this._prepareRenderingGroup(renderingGroupId);
  17764. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  17765. };
  17766. /**
  17767. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  17768. * This allowed control for front to back rendering or reversly depending of the special needs.
  17769. *
  17770. * @param renderingGroupId The rendering group id corresponding to its index
  17771. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  17772. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  17773. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  17774. */
  17775. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  17776. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  17777. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  17778. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  17779. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  17780. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  17781. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  17782. if (this._renderingGroups[renderingGroupId]) {
  17783. var group = this._renderingGroups[renderingGroupId];
  17784. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  17785. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  17786. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  17787. }
  17788. };
  17789. /**
  17790. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  17791. *
  17792. * @param renderingGroupId The rendering group id corresponding to its index
  17793. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  17794. * @param depth Automatically clears depth between groups if true and autoClear is true.
  17795. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  17796. */
  17797. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  17798. if (depth === void 0) { depth = true; }
  17799. if (stencil === void 0) { stencil = true; }
  17800. this._autoClearDepthStencil[renderingGroupId] = {
  17801. autoClear: autoClearDepthStencil,
  17802. depth: depth,
  17803. stencil: stencil
  17804. };
  17805. };
  17806. /**
  17807. * The max id used for rendering groups (not included)
  17808. */
  17809. RenderingManager.MAX_RENDERINGGROUPS = 4;
  17810. /**
  17811. * The min id used for rendering groups (included)
  17812. */
  17813. RenderingManager.MIN_RENDERINGGROUPS = 0;
  17814. /**
  17815. * Used to globally prevent autoclearing scenes.
  17816. */
  17817. RenderingManager.AUTOCLEAR = true;
  17818. return RenderingManager;
  17819. }());
  17820. BABYLON.RenderingManager = RenderingManager;
  17821. })(BABYLON || (BABYLON = {}));
  17822. //# sourceMappingURL=babylon.renderingManager.js.map
  17823. var BABYLON;
  17824. (function (BABYLON) {
  17825. var RenderingGroup = /** @class */ (function () {
  17826. /**
  17827. * Creates a new rendering group.
  17828. * @param index The rendering group index
  17829. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  17830. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  17831. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  17832. */
  17833. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  17834. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  17835. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  17836. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  17837. this.index = index;
  17838. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  17839. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  17840. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  17841. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  17842. this._particleSystems = new BABYLON.SmartArray(256);
  17843. this._spriteManagers = new BABYLON.SmartArray(256);
  17844. this._edgesRenderers = new BABYLON.SmartArray(16);
  17845. this._scene = scene;
  17846. this.opaqueSortCompareFn = opaqueSortCompareFn;
  17847. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  17848. this.transparentSortCompareFn = transparentSortCompareFn;
  17849. }
  17850. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  17851. /**
  17852. * Set the opaque sort comparison function.
  17853. * If null the sub meshes will be render in the order they were created
  17854. */
  17855. set: function (value) {
  17856. this._opaqueSortCompareFn = value;
  17857. if (value) {
  17858. this._renderOpaque = this.renderOpaqueSorted;
  17859. }
  17860. else {
  17861. this._renderOpaque = RenderingGroup.renderUnsorted;
  17862. }
  17863. },
  17864. enumerable: true,
  17865. configurable: true
  17866. });
  17867. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  17868. /**
  17869. * Set the alpha test sort comparison function.
  17870. * If null the sub meshes will be render in the order they were created
  17871. */
  17872. set: function (value) {
  17873. this._alphaTestSortCompareFn = value;
  17874. if (value) {
  17875. this._renderAlphaTest = this.renderAlphaTestSorted;
  17876. }
  17877. else {
  17878. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  17879. }
  17880. },
  17881. enumerable: true,
  17882. configurable: true
  17883. });
  17884. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  17885. /**
  17886. * Set the transparent sort comparison function.
  17887. * If null the sub meshes will be render in the order they were created
  17888. */
  17889. set: function (value) {
  17890. if (value) {
  17891. this._transparentSortCompareFn = value;
  17892. }
  17893. else {
  17894. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  17895. }
  17896. this._renderTransparent = this.renderTransparentSorted;
  17897. },
  17898. enumerable: true,
  17899. configurable: true
  17900. });
  17901. /**
  17902. * Render all the sub meshes contained in the group.
  17903. * @param customRenderFunction Used to override the default render behaviour of the group.
  17904. * @returns true if rendered some submeshes.
  17905. */
  17906. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  17907. if (customRenderFunction) {
  17908. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  17909. return;
  17910. }
  17911. var engine = this._scene.getEngine();
  17912. // Depth only
  17913. if (this._depthOnlySubMeshes.length !== 0) {
  17914. engine.setAlphaTesting(true);
  17915. engine.setColorWrite(false);
  17916. this._renderAlphaTest(this._depthOnlySubMeshes);
  17917. engine.setAlphaTesting(false);
  17918. engine.setColorWrite(true);
  17919. }
  17920. // Opaque
  17921. if (this._opaqueSubMeshes.length !== 0) {
  17922. this._renderOpaque(this._opaqueSubMeshes);
  17923. }
  17924. // Alpha test
  17925. if (this._alphaTestSubMeshes.length !== 0) {
  17926. engine.setAlphaTesting(true);
  17927. this._renderAlphaTest(this._alphaTestSubMeshes);
  17928. engine.setAlphaTesting(false);
  17929. }
  17930. var stencilState = engine.getStencilBuffer();
  17931. engine.setStencilBuffer(false);
  17932. // Sprites
  17933. if (renderSprites) {
  17934. this._renderSprites();
  17935. }
  17936. // Particles
  17937. if (renderParticles) {
  17938. this._renderParticles(activeMeshes);
  17939. }
  17940. if (this.onBeforeTransparentRendering) {
  17941. this.onBeforeTransparentRendering();
  17942. }
  17943. // Transparent
  17944. if (this._transparentSubMeshes.length !== 0) {
  17945. this._renderTransparent(this._transparentSubMeshes);
  17946. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  17947. }
  17948. // Set back stencil to false in case it changes before the edge renderer.
  17949. engine.setStencilBuffer(false);
  17950. // Edges
  17951. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  17952. this._edgesRenderers.data[edgesRendererIndex].render();
  17953. }
  17954. // Restore Stencil state.
  17955. engine.setStencilBuffer(stencilState);
  17956. };
  17957. /**
  17958. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  17959. * @param subMeshes The submeshes to render
  17960. */
  17961. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  17962. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  17963. };
  17964. /**
  17965. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  17966. * @param subMeshes The submeshes to render
  17967. */
  17968. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  17969. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  17970. };
  17971. /**
  17972. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  17973. * @param subMeshes The submeshes to render
  17974. */
  17975. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  17976. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  17977. };
  17978. /**
  17979. * Renders the submeshes in a specified order.
  17980. * @param subMeshes The submeshes to sort before render
  17981. * @param sortCompareFn The comparison function use to sort
  17982. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  17983. * @param transparent Specifies to activate blending if true
  17984. */
  17985. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  17986. var subIndex = 0;
  17987. var subMesh;
  17988. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  17989. for (; subIndex < subMeshes.length; subIndex++) {
  17990. subMesh = subMeshes.data[subIndex];
  17991. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  17992. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  17993. }
  17994. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  17995. if (sortCompareFn) {
  17996. sortedArray.sort(sortCompareFn);
  17997. }
  17998. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  17999. subMesh = sortedArray[subIndex];
  18000. if (transparent) {
  18001. var material = subMesh.getMaterial();
  18002. if (material && material.needDepthPrePass) {
  18003. var engine = material.getScene().getEngine();
  18004. engine.setColorWrite(false);
  18005. engine.setAlphaTesting(true);
  18006. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  18007. subMesh.render(false);
  18008. engine.setAlphaTesting(false);
  18009. engine.setColorWrite(true);
  18010. }
  18011. }
  18012. subMesh.render(transparent);
  18013. }
  18014. };
  18015. /**
  18016. * Renders the submeshes in the order they were dispatched (no sort applied).
  18017. * @param subMeshes The submeshes to render
  18018. */
  18019. RenderingGroup.renderUnsorted = function (subMeshes) {
  18020. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  18021. var submesh = subMeshes.data[subIndex];
  18022. submesh.render(false);
  18023. }
  18024. };
  18025. /**
  18026. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  18027. * are rendered back to front if in the same alpha index.
  18028. *
  18029. * @param a The first submesh
  18030. * @param b The second submesh
  18031. * @returns The result of the comparison
  18032. */
  18033. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  18034. // Alpha index first
  18035. if (a._alphaIndex > b._alphaIndex) {
  18036. return 1;
  18037. }
  18038. if (a._alphaIndex < b._alphaIndex) {
  18039. return -1;
  18040. }
  18041. // Then distance to camera
  18042. return RenderingGroup.backToFrontSortCompare(a, b);
  18043. };
  18044. /**
  18045. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  18046. * are rendered back to front.
  18047. *
  18048. * @param a The first submesh
  18049. * @param b The second submesh
  18050. * @returns The result of the comparison
  18051. */
  18052. RenderingGroup.backToFrontSortCompare = function (a, b) {
  18053. // Then distance to camera
  18054. if (a._distanceToCamera < b._distanceToCamera) {
  18055. return 1;
  18056. }
  18057. if (a._distanceToCamera > b._distanceToCamera) {
  18058. return -1;
  18059. }
  18060. return 0;
  18061. };
  18062. /**
  18063. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  18064. * are rendered front to back (prevent overdraw).
  18065. *
  18066. * @param a The first submesh
  18067. * @param b The second submesh
  18068. * @returns The result of the comparison
  18069. */
  18070. RenderingGroup.frontToBackSortCompare = function (a, b) {
  18071. // Then distance to camera
  18072. if (a._distanceToCamera < b._distanceToCamera) {
  18073. return -1;
  18074. }
  18075. if (a._distanceToCamera > b._distanceToCamera) {
  18076. return 1;
  18077. }
  18078. return 0;
  18079. };
  18080. /**
  18081. * Resets the different lists of submeshes to prepare a new frame.
  18082. */
  18083. RenderingGroup.prototype.prepare = function () {
  18084. this._opaqueSubMeshes.reset();
  18085. this._transparentSubMeshes.reset();
  18086. this._alphaTestSubMeshes.reset();
  18087. this._depthOnlySubMeshes.reset();
  18088. this._particleSystems.reset();
  18089. this._spriteManagers.reset();
  18090. this._edgesRenderers.reset();
  18091. };
  18092. RenderingGroup.prototype.dispose = function () {
  18093. this._opaqueSubMeshes.dispose();
  18094. this._transparentSubMeshes.dispose();
  18095. this._alphaTestSubMeshes.dispose();
  18096. this._depthOnlySubMeshes.dispose();
  18097. this._particleSystems.dispose();
  18098. this._spriteManagers.dispose();
  18099. this._edgesRenderers.dispose();
  18100. };
  18101. /**
  18102. * Inserts the submesh in its correct queue depending on its material.
  18103. * @param subMesh The submesh to dispatch
  18104. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  18105. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  18106. */
  18107. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  18108. // Get mesh and materials if not provided
  18109. if (mesh === undefined) {
  18110. mesh = subMesh.getMesh();
  18111. }
  18112. if (material === undefined) {
  18113. material = subMesh.getMaterial();
  18114. }
  18115. if (material === null || material === undefined) {
  18116. return;
  18117. }
  18118. if (material.needAlphaBlendingForMesh(mesh)) {
  18119. this._transparentSubMeshes.push(subMesh);
  18120. }
  18121. else if (material.needAlphaTesting()) {
  18122. if (material.needDepthPrePass === true) {
  18123. this._depthOnlySubMeshes.push(subMesh);
  18124. }
  18125. this._alphaTestSubMeshes.push(subMesh);
  18126. }
  18127. else {
  18128. if (material.needDepthPrePass === true) {
  18129. this._depthOnlySubMeshes.push(subMesh);
  18130. }
  18131. this._opaqueSubMeshes.push(subMesh); // Opaque
  18132. }
  18133. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined) {
  18134. this._edgesRenderers.push(mesh._edgesRenderer);
  18135. }
  18136. };
  18137. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  18138. this._spriteManagers.push(spriteManager);
  18139. };
  18140. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  18141. this._particleSystems.push(particleSystem);
  18142. };
  18143. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  18144. if (this._particleSystems.length === 0) {
  18145. return;
  18146. }
  18147. // Particles
  18148. var activeCamera = this._scene.activeCamera;
  18149. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  18150. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  18151. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  18152. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  18153. continue;
  18154. }
  18155. var emitter = particleSystem.emitter;
  18156. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  18157. this._scene._activeParticles.addCount(particleSystem.render(), false);
  18158. }
  18159. }
  18160. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  18161. };
  18162. RenderingGroup.prototype._renderSprites = function () {
  18163. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  18164. return;
  18165. }
  18166. // Sprites
  18167. var activeCamera = this._scene.activeCamera;
  18168. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  18169. for (var id = 0; id < this._spriteManagers.length; id++) {
  18170. var spriteManager = this._spriteManagers.data[id];
  18171. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  18172. spriteManager.render();
  18173. }
  18174. }
  18175. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  18176. };
  18177. return RenderingGroup;
  18178. }());
  18179. BABYLON.RenderingGroup = RenderingGroup;
  18180. })(BABYLON || (BABYLON = {}));
  18181. //# sourceMappingURL=babylon.renderingGroup.js.map
  18182. var BABYLON;
  18183. (function (BABYLON) {
  18184. var ClickInfo = /** @class */ (function () {
  18185. function ClickInfo() {
  18186. this._singleClick = false;
  18187. this._doubleClick = false;
  18188. this._hasSwiped = false;
  18189. this._ignore = false;
  18190. }
  18191. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  18192. get: function () {
  18193. return this._singleClick;
  18194. },
  18195. set: function (b) {
  18196. this._singleClick = b;
  18197. },
  18198. enumerable: true,
  18199. configurable: true
  18200. });
  18201. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  18202. get: function () {
  18203. return this._doubleClick;
  18204. },
  18205. set: function (b) {
  18206. this._doubleClick = b;
  18207. },
  18208. enumerable: true,
  18209. configurable: true
  18210. });
  18211. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  18212. get: function () {
  18213. return this._hasSwiped;
  18214. },
  18215. set: function (b) {
  18216. this._hasSwiped = b;
  18217. },
  18218. enumerable: true,
  18219. configurable: true
  18220. });
  18221. Object.defineProperty(ClickInfo.prototype, "ignore", {
  18222. get: function () {
  18223. return this._ignore;
  18224. },
  18225. set: function (b) {
  18226. this._ignore = b;
  18227. },
  18228. enumerable: true,
  18229. configurable: true
  18230. });
  18231. return ClickInfo;
  18232. }());
  18233. /**
  18234. * This class is used by the onRenderingGroupObservable
  18235. */
  18236. var RenderingGroupInfo = /** @class */ (function () {
  18237. function RenderingGroupInfo() {
  18238. }
  18239. /**
  18240. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  18241. * This stage will be fired no matter what
  18242. */
  18243. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  18244. /**
  18245. * Called before opaque object are rendered.
  18246. * This stage will be fired only if there's 3D Opaque content to render
  18247. */
  18248. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  18249. /**
  18250. * Called after the opaque objects are rendered and before the transparent ones
  18251. * This stage will be fired only if there's 3D transparent content to render
  18252. */
  18253. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  18254. /**
  18255. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  18256. * This stage will be fired no matter what
  18257. */
  18258. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  18259. return RenderingGroupInfo;
  18260. }());
  18261. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  18262. /**
  18263. * Represents a scene to be rendered by the engine.
  18264. * @see http://doc.babylonjs.com/page.php?p=21911
  18265. */
  18266. var Scene = /** @class */ (function () {
  18267. /**
  18268. * @constructor
  18269. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  18270. */
  18271. function Scene(engine) {
  18272. // Members
  18273. this.autoClear = true;
  18274. this.autoClearDepthAndStencil = true;
  18275. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  18276. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  18277. this.forceWireframe = false;
  18278. this._forcePointsCloud = false;
  18279. this.forceShowBoundingBoxes = false;
  18280. this.animationsEnabled = true;
  18281. this.useConstantAnimationDeltaTime = false;
  18282. this.constantlyUpdateMeshUnderPointer = false;
  18283. this.hoverCursor = "pointer";
  18284. this.defaultCursor = "";
  18285. /**
  18286. * This is used to call preventDefault() on pointer down
  18287. * in order to block unwanted artifacts like system double clicks
  18288. */
  18289. this.preventDefaultOnPointerDown = true;
  18290. // Metadata
  18291. this.metadata = null;
  18292. /**
  18293. * An event triggered when the scene is disposed.
  18294. * @type {BABYLON.Observable}
  18295. */
  18296. this.onDisposeObservable = new BABYLON.Observable();
  18297. /**
  18298. * An event triggered before rendering the scene (right after animations and physics)
  18299. * @type {BABYLON.Observable}
  18300. */
  18301. this.onBeforeRenderObservable = new BABYLON.Observable();
  18302. /**
  18303. * An event triggered after rendering the scene
  18304. * @type {BABYLON.Observable}
  18305. */
  18306. this.onAfterRenderObservable = new BABYLON.Observable();
  18307. /**
  18308. * An event triggered before animating the scene
  18309. * @type {BABYLON.Observable}
  18310. */
  18311. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  18312. /**
  18313. * An event triggered after animations processing
  18314. * @type {BABYLON.Observable}
  18315. */
  18316. this.onAfterAnimationsObservable = new BABYLON.Observable();
  18317. /**
  18318. * An event triggered before draw calls are ready to be sent
  18319. * @type {BABYLON.Observable}
  18320. */
  18321. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  18322. /**
  18323. * An event triggered after draw calls have been sent
  18324. * @type {BABYLON.Observable}
  18325. */
  18326. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  18327. /**
  18328. * An event triggered when physic simulation is about to be run
  18329. * @type {BABYLON.Observable}
  18330. */
  18331. this.onBeforePhysicsObservable = new BABYLON.Observable();
  18332. /**
  18333. * An event triggered when physic simulation has been done
  18334. * @type {BABYLON.Observable}
  18335. */
  18336. this.onAfterPhysicsObservable = new BABYLON.Observable();
  18337. /**
  18338. * An event triggered when the scene is ready
  18339. * @type {BABYLON.Observable}
  18340. */
  18341. this.onReadyObservable = new BABYLON.Observable();
  18342. /**
  18343. * An event triggered before rendering a camera
  18344. * @type {BABYLON.Observable}
  18345. */
  18346. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  18347. /**
  18348. * An event triggered after rendering a camera
  18349. * @type {BABYLON.Observable}
  18350. */
  18351. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  18352. /**
  18353. * An event triggered when active meshes evaluation is about to start
  18354. * @type {BABYLON.Observable}
  18355. */
  18356. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  18357. /**
  18358. * An event triggered when active meshes evaluation is done
  18359. * @type {BABYLON.Observable}
  18360. */
  18361. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  18362. /**
  18363. * An event triggered when particles rendering is about to start
  18364. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  18365. * @type {BABYLON.Observable}
  18366. */
  18367. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  18368. /**
  18369. * An event triggered when particles rendering is done
  18370. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  18371. * @type {BABYLON.Observable}
  18372. */
  18373. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  18374. /**
  18375. * An event triggered when sprites rendering is about to start
  18376. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  18377. * @type {BABYLON.Observable}
  18378. */
  18379. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  18380. /**
  18381. * An event triggered when sprites rendering is done
  18382. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  18383. * @type {BABYLON.Observable}
  18384. */
  18385. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  18386. /**
  18387. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  18388. * @type {BABYLON.Observable}
  18389. */
  18390. this.onDataLoadedObservable = new BABYLON.Observable();
  18391. /**
  18392. * An event triggered when a camera is created
  18393. * @type {BABYLON.Observable}
  18394. */
  18395. this.onNewCameraAddedObservable = new BABYLON.Observable();
  18396. /**
  18397. * An event triggered when a camera is removed
  18398. * @type {BABYLON.Observable}
  18399. */
  18400. this.onCameraRemovedObservable = new BABYLON.Observable();
  18401. /**
  18402. * An event triggered when a light is created
  18403. * @type {BABYLON.Observable}
  18404. */
  18405. this.onNewLightAddedObservable = new BABYLON.Observable();
  18406. /**
  18407. * An event triggered when a light is removed
  18408. * @type {BABYLON.Observable}
  18409. */
  18410. this.onLightRemovedObservable = new BABYLON.Observable();
  18411. /**
  18412. * An event triggered when a geometry is created
  18413. * @type {BABYLON.Observable}
  18414. */
  18415. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  18416. /**
  18417. * An event triggered when a geometry is removed
  18418. * @type {BABYLON.Observable}
  18419. */
  18420. this.onGeometryRemovedObservable = new BABYLON.Observable();
  18421. /**
  18422. * An event triggered when a transform node is created
  18423. * @type {BABYLON.Observable}
  18424. */
  18425. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  18426. /**
  18427. * An event triggered when a transform node is removed
  18428. * @type {BABYLON.Observable}
  18429. */
  18430. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  18431. /**
  18432. * An event triggered when a mesh is created
  18433. * @type {BABYLON.Observable}
  18434. */
  18435. this.onNewMeshAddedObservable = new BABYLON.Observable();
  18436. /**
  18437. * An event triggered when a mesh is removed
  18438. * @type {BABYLON.Observable}
  18439. */
  18440. this.onMeshRemovedObservable = new BABYLON.Observable();
  18441. /**
  18442. * An event triggered when render targets are about to be rendered
  18443. * Can happen multiple times per frame.
  18444. * @type {BABYLON.Observable}
  18445. */
  18446. this.OnBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  18447. /**
  18448. * An event triggered when render targets were rendered.
  18449. * Can happen multiple times per frame.
  18450. * @type {BABYLON.Observable}
  18451. */
  18452. this.OnAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  18453. /**
  18454. * An event triggered before calculating deterministic simulation step
  18455. * @type {BABYLON.Observable}
  18456. */
  18457. this.onBeforeStepObservable = new BABYLON.Observable();
  18458. /**
  18459. * An event triggered after calculating deterministic simulation step
  18460. * @type {BABYLON.Observable}
  18461. */
  18462. this.onAfterStepObservable = new BABYLON.Observable();
  18463. /**
  18464. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  18465. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  18466. * 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)
  18467. */
  18468. this.onRenderingGroupObservable = new BABYLON.Observable();
  18469. // Animations
  18470. this.animations = [];
  18471. /**
  18472. * 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).
  18473. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  18474. */
  18475. this.onPrePointerObservable = new BABYLON.Observable();
  18476. /**
  18477. * Observable event triggered each time an input event is received from the rendering canvas
  18478. */
  18479. this.onPointerObservable = new BABYLON.Observable();
  18480. this._meshPickProceed = false;
  18481. this._currentPickResult = null;
  18482. this._previousPickResult = null;
  18483. this._totalPointersPressed = 0;
  18484. this._doubleClickOccured = false;
  18485. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  18486. this.cameraToUseForPointers = null;
  18487. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  18488. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  18489. this._startingPointerTime = 0;
  18490. this._previousStartingPointerTime = 0;
  18491. // Deterministic lockstep
  18492. this._timeAccumulator = 0;
  18493. this._currentStepId = 0;
  18494. this._currentInternalStep = 0;
  18495. // Keyboard
  18496. /**
  18497. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  18498. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  18499. */
  18500. this.onPreKeyboardObservable = new BABYLON.Observable();
  18501. /**
  18502. * Observable event triggered each time an keyboard event is received from the hosting window
  18503. */
  18504. this.onKeyboardObservable = new BABYLON.Observable();
  18505. // Coordinate system
  18506. /**
  18507. * use right-handed coordinate system on this scene.
  18508. * @type {boolean}
  18509. */
  18510. this._useRightHandedSystem = false;
  18511. // Fog
  18512. this._fogEnabled = true;
  18513. this._fogMode = Scene.FOGMODE_NONE;
  18514. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  18515. this.fogDensity = 0.1;
  18516. this.fogStart = 0;
  18517. this.fogEnd = 1000.0;
  18518. // Lights
  18519. /**
  18520. * is shadow enabled on this scene.
  18521. * @type {boolean}
  18522. */
  18523. this._shadowsEnabled = true;
  18524. /**
  18525. * is light enabled on this scene.
  18526. * @type {boolean}
  18527. */
  18528. this._lightsEnabled = true;
  18529. /**
  18530. * All of the lights added to this scene.
  18531. * @see BABYLON.Light
  18532. * @type {BABYLON.Light[]}
  18533. */
  18534. this.lights = new Array();
  18535. // Cameras
  18536. /** All of the cameras added to this scene. */
  18537. this.cameras = new Array();
  18538. /** All of the active cameras added to this scene. */
  18539. this.activeCameras = new Array();
  18540. // Meshes
  18541. /**
  18542. * All of the tranform nodes added to this scene.
  18543. * @see BABYLON.TransformNode
  18544. * @type {BABYLON.TransformNode[]}
  18545. */
  18546. this.transformNodes = new Array();
  18547. /**
  18548. * All of the (abstract) meshes added to this scene.
  18549. * @see BABYLON.AbstractMesh
  18550. * @type {BABYLON.AbstractMesh[]}
  18551. */
  18552. this.meshes = new Array();
  18553. /**
  18554. * All of the animation groups added to this scene.
  18555. * @see BABYLON.AnimationGroup
  18556. * @type {BABYLON.AnimationGroup[]}
  18557. */
  18558. this.animationGroups = new Array();
  18559. // Geometries
  18560. this._geometries = new Array();
  18561. this.materials = new Array();
  18562. this.multiMaterials = new Array();
  18563. // Textures
  18564. this._texturesEnabled = true;
  18565. this.textures = new Array();
  18566. // Particles
  18567. this.particlesEnabled = true;
  18568. this.particleSystems = new Array();
  18569. // Sprites
  18570. this.spritesEnabled = true;
  18571. this.spriteManagers = new Array();
  18572. // Layers
  18573. this.layers = new Array();
  18574. this.highlightLayers = new Array();
  18575. // Skeletons
  18576. this._skeletonsEnabled = true;
  18577. this.skeletons = new Array();
  18578. // Morph targets
  18579. this.morphTargetManagers = new Array();
  18580. // Lens flares
  18581. this.lensFlaresEnabled = true;
  18582. this.lensFlareSystems = new Array();
  18583. // Collisions
  18584. this.collisionsEnabled = true;
  18585. /** Defines the gravity applied to this scene */
  18586. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  18587. // Postprocesses
  18588. this.postProcesses = new Array();
  18589. this.postProcessesEnabled = true;
  18590. // Customs render targets
  18591. this.renderTargetsEnabled = true;
  18592. this.dumpNextRenderTargets = false;
  18593. this.customRenderTargets = new Array();
  18594. // Imported meshes
  18595. this.importedMeshesFiles = new Array();
  18596. // Probes
  18597. this.probesEnabled = true;
  18598. this.reflectionProbes = new Array();
  18599. this._actionManagers = new Array();
  18600. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  18601. // Procedural textures
  18602. this.proceduralTexturesEnabled = true;
  18603. this._proceduralTextures = new Array();
  18604. this.soundTracks = new Array();
  18605. this._audioEnabled = true;
  18606. this._headphone = false;
  18607. // Performance counters
  18608. this._totalVertices = new BABYLON.PerfCounter();
  18609. this._activeIndices = new BABYLON.PerfCounter();
  18610. this._activeParticles = new BABYLON.PerfCounter();
  18611. this._activeBones = new BABYLON.PerfCounter();
  18612. this._animationTime = 0;
  18613. this.animationTimeScale = 1;
  18614. this._renderId = 0;
  18615. this._executeWhenReadyTimeoutId = -1;
  18616. this._intermediateRendering = false;
  18617. this._viewUpdateFlag = -1;
  18618. this._projectionUpdateFlag = -1;
  18619. this._alternateViewUpdateFlag = -1;
  18620. this._alternateProjectionUpdateFlag = -1;
  18621. this._toBeDisposed = new BABYLON.SmartArray(256);
  18622. this._activeRequests = new Array();
  18623. this._pendingData = new Array();
  18624. this._isDisposed = false;
  18625. this.dispatchAllSubMeshesOfActiveMeshes = false;
  18626. this._activeMeshes = new BABYLON.SmartArray(256);
  18627. this._processedMaterials = new BABYLON.SmartArray(256);
  18628. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  18629. this._activeParticleSystems = new BABYLON.SmartArray(256);
  18630. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  18631. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  18632. this._activeAnimatables = new Array();
  18633. this._transformMatrix = BABYLON.Matrix.Zero();
  18634. this._useAlternateCameraConfiguration = false;
  18635. this._alternateRendering = false;
  18636. this.requireLightSorting = false;
  18637. this._activeMeshesFrozen = false;
  18638. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  18639. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  18640. this._engine.scenes.push(this);
  18641. this._uid = null;
  18642. this._renderingManager = new BABYLON.RenderingManager(this);
  18643. this.postProcessManager = new BABYLON.PostProcessManager(this);
  18644. if (BABYLON.OutlineRenderer) {
  18645. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  18646. }
  18647. if (BABYLON.Tools.IsWindowObjectExist()) {
  18648. this.attachControl();
  18649. }
  18650. //simplification queue
  18651. if (BABYLON.SimplificationQueue) {
  18652. this.simplificationQueue = new BABYLON.SimplificationQueue();
  18653. }
  18654. //collision coordinator initialization. For now legacy per default.
  18655. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  18656. // Uniform Buffer
  18657. this._createUbo();
  18658. // Default Image processing definition.
  18659. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  18660. }
  18661. Object.defineProperty(Scene, "FOGMODE_NONE", {
  18662. /** The fog is deactivated */
  18663. get: function () {
  18664. return Scene._FOGMODE_NONE;
  18665. },
  18666. enumerable: true,
  18667. configurable: true
  18668. });
  18669. Object.defineProperty(Scene, "FOGMODE_EXP", {
  18670. /** The fog density is following an exponential function */
  18671. get: function () {
  18672. return Scene._FOGMODE_EXP;
  18673. },
  18674. enumerable: true,
  18675. configurable: true
  18676. });
  18677. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  18678. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  18679. get: function () {
  18680. return Scene._FOGMODE_EXP2;
  18681. },
  18682. enumerable: true,
  18683. configurable: true
  18684. });
  18685. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  18686. /** The fog density is following a linear function. */
  18687. get: function () {
  18688. return Scene._FOGMODE_LINEAR;
  18689. },
  18690. enumerable: true,
  18691. configurable: true
  18692. });
  18693. Object.defineProperty(Scene.prototype, "environmentTexture", {
  18694. /**
  18695. * Texture used in all pbr material as the reflection texture.
  18696. * As in the majority of the scene they are the same (exception for multi room and so on),
  18697. * this is easier to reference from here than from all the materials.
  18698. */
  18699. get: function () {
  18700. return this._environmentTexture;
  18701. },
  18702. /**
  18703. * Texture used in all pbr material as the reflection texture.
  18704. * As in the majority of the scene they are the same (exception for multi room and so on),
  18705. * this is easier to set here than in all the materials.
  18706. */
  18707. set: function (value) {
  18708. if (this._environmentTexture === value) {
  18709. return;
  18710. }
  18711. this._environmentTexture = value;
  18712. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  18713. },
  18714. enumerable: true,
  18715. configurable: true
  18716. });
  18717. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  18718. /**
  18719. * Default image processing configuration used either in the rendering
  18720. * Forward main pass or through the imageProcessingPostProcess if present.
  18721. * As in the majority of the scene they are the same (exception for multi camera),
  18722. * this is easier to reference from here than from all the materials and post process.
  18723. *
  18724. * No setter as we it is a shared configuration, you can set the values instead.
  18725. */
  18726. get: function () {
  18727. return this._imageProcessingConfiguration;
  18728. },
  18729. enumerable: true,
  18730. configurable: true
  18731. });
  18732. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  18733. get: function () {
  18734. return this._forcePointsCloud;
  18735. },
  18736. set: function (value) {
  18737. if (this._forcePointsCloud === value) {
  18738. return;
  18739. }
  18740. this._forcePointsCloud = value;
  18741. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  18742. },
  18743. enumerable: true,
  18744. configurable: true
  18745. });
  18746. Object.defineProperty(Scene.prototype, "onDispose", {
  18747. /** A function to be executed when this scene is disposed. */
  18748. set: function (callback) {
  18749. if (this._onDisposeObserver) {
  18750. this.onDisposeObservable.remove(this._onDisposeObserver);
  18751. }
  18752. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  18753. },
  18754. enumerable: true,
  18755. configurable: true
  18756. });
  18757. Object.defineProperty(Scene.prototype, "beforeRender", {
  18758. /** A function to be executed before rendering this scene */
  18759. set: function (callback) {
  18760. if (this._onBeforeRenderObserver) {
  18761. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  18762. }
  18763. if (callback) {
  18764. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  18765. }
  18766. },
  18767. enumerable: true,
  18768. configurable: true
  18769. });
  18770. Object.defineProperty(Scene.prototype, "afterRender", {
  18771. /** A function to be executed after rendering this scene */
  18772. set: function (callback) {
  18773. if (this._onAfterRenderObserver) {
  18774. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  18775. }
  18776. if (callback) {
  18777. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  18778. }
  18779. },
  18780. enumerable: true,
  18781. configurable: true
  18782. });
  18783. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  18784. set: function (callback) {
  18785. if (this._onBeforeCameraRenderObserver) {
  18786. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  18787. }
  18788. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  18789. },
  18790. enumerable: true,
  18791. configurable: true
  18792. });
  18793. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  18794. set: function (callback) {
  18795. if (this._onAfterCameraRenderObserver) {
  18796. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  18797. }
  18798. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  18799. },
  18800. enumerable: true,
  18801. configurable: true
  18802. });
  18803. Object.defineProperty(Scene.prototype, "gamepadManager", {
  18804. get: function () {
  18805. if (!this._gamepadManager) {
  18806. this._gamepadManager = new BABYLON.GamepadManager(this);
  18807. }
  18808. return this._gamepadManager;
  18809. },
  18810. enumerable: true,
  18811. configurable: true
  18812. });
  18813. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  18814. get: function () {
  18815. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  18816. },
  18817. enumerable: true,
  18818. configurable: true
  18819. });
  18820. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  18821. get: function () {
  18822. return this._useRightHandedSystem;
  18823. },
  18824. set: function (value) {
  18825. if (this._useRightHandedSystem === value) {
  18826. return;
  18827. }
  18828. this._useRightHandedSystem = value;
  18829. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  18830. },
  18831. enumerable: true,
  18832. configurable: true
  18833. });
  18834. Scene.prototype.setStepId = function (newStepId) {
  18835. this._currentStepId = newStepId;
  18836. };
  18837. ;
  18838. Scene.prototype.getStepId = function () {
  18839. return this._currentStepId;
  18840. };
  18841. ;
  18842. Scene.prototype.getInternalStep = function () {
  18843. return this._currentInternalStep;
  18844. };
  18845. ;
  18846. Object.defineProperty(Scene.prototype, "fogEnabled", {
  18847. get: function () {
  18848. return this._fogEnabled;
  18849. },
  18850. /**
  18851. * is fog enabled on this scene.
  18852. */
  18853. set: function (value) {
  18854. if (this._fogEnabled === value) {
  18855. return;
  18856. }
  18857. this._fogEnabled = value;
  18858. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  18859. },
  18860. enumerable: true,
  18861. configurable: true
  18862. });
  18863. Object.defineProperty(Scene.prototype, "fogMode", {
  18864. get: function () {
  18865. return this._fogMode;
  18866. },
  18867. set: function (value) {
  18868. if (this._fogMode === value) {
  18869. return;
  18870. }
  18871. this._fogMode = value;
  18872. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  18873. },
  18874. enumerable: true,
  18875. configurable: true
  18876. });
  18877. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  18878. get: function () {
  18879. return this._shadowsEnabled;
  18880. },
  18881. set: function (value) {
  18882. if (this._shadowsEnabled === value) {
  18883. return;
  18884. }
  18885. this._shadowsEnabled = value;
  18886. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  18887. },
  18888. enumerable: true,
  18889. configurable: true
  18890. });
  18891. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  18892. get: function () {
  18893. return this._lightsEnabled;
  18894. },
  18895. set: function (value) {
  18896. if (this._lightsEnabled === value) {
  18897. return;
  18898. }
  18899. this._lightsEnabled = value;
  18900. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  18901. },
  18902. enumerable: true,
  18903. configurable: true
  18904. });
  18905. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  18906. /** The default material used on meshes when no material is affected */
  18907. get: function () {
  18908. if (!this._defaultMaterial) {
  18909. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  18910. }
  18911. return this._defaultMaterial;
  18912. },
  18913. /** The default material used on meshes when no material is affected */
  18914. set: function (value) {
  18915. this._defaultMaterial = value;
  18916. },
  18917. enumerable: true,
  18918. configurable: true
  18919. });
  18920. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  18921. get: function () {
  18922. return this._texturesEnabled;
  18923. },
  18924. set: function (value) {
  18925. if (this._texturesEnabled === value) {
  18926. return;
  18927. }
  18928. this._texturesEnabled = value;
  18929. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  18930. },
  18931. enumerable: true,
  18932. configurable: true
  18933. });
  18934. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  18935. get: function () {
  18936. return this._skeletonsEnabled;
  18937. },
  18938. set: function (value) {
  18939. if (this._skeletonsEnabled === value) {
  18940. return;
  18941. }
  18942. this._skeletonsEnabled = value;
  18943. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  18944. },
  18945. enumerable: true,
  18946. configurable: true
  18947. });
  18948. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  18949. get: function () {
  18950. if (!this._postProcessRenderPipelineManager) {
  18951. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  18952. }
  18953. return this._postProcessRenderPipelineManager;
  18954. },
  18955. enumerable: true,
  18956. configurable: true
  18957. });
  18958. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  18959. get: function () {
  18960. if (!this._mainSoundTrack) {
  18961. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  18962. }
  18963. return this._mainSoundTrack;
  18964. },
  18965. enumerable: true,
  18966. configurable: true
  18967. });
  18968. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  18969. get: function () {
  18970. return this._alternateRendering;
  18971. },
  18972. enumerable: true,
  18973. configurable: true
  18974. });
  18975. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  18976. get: function () {
  18977. return this._frustumPlanes;
  18978. },
  18979. enumerable: true,
  18980. configurable: true
  18981. });
  18982. Object.defineProperty(Scene.prototype, "debugLayer", {
  18983. // Properties
  18984. get: function () {
  18985. if (!this._debugLayer) {
  18986. this._debugLayer = new BABYLON.DebugLayer(this);
  18987. }
  18988. return this._debugLayer;
  18989. },
  18990. enumerable: true,
  18991. configurable: true
  18992. });
  18993. Object.defineProperty(Scene.prototype, "workerCollisions", {
  18994. get: function () {
  18995. return this._workerCollisions;
  18996. },
  18997. set: function (enabled) {
  18998. if (!BABYLON.CollisionCoordinatorLegacy) {
  18999. return;
  19000. }
  19001. enabled = (enabled && !!Worker);
  19002. this._workerCollisions = enabled;
  19003. if (this.collisionCoordinator) {
  19004. this.collisionCoordinator.destroy();
  19005. }
  19006. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  19007. this.collisionCoordinator.init(this);
  19008. },
  19009. enumerable: true,
  19010. configurable: true
  19011. });
  19012. Object.defineProperty(Scene.prototype, "selectionOctree", {
  19013. get: function () {
  19014. return this._selectionOctree;
  19015. },
  19016. enumerable: true,
  19017. configurable: true
  19018. });
  19019. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  19020. /**
  19021. * The mesh that is currently under the pointer.
  19022. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  19023. */
  19024. get: function () {
  19025. return this._pointerOverMesh;
  19026. },
  19027. enumerable: true,
  19028. configurable: true
  19029. });
  19030. Object.defineProperty(Scene.prototype, "pointerX", {
  19031. /**
  19032. * Current on-screen X position of the pointer
  19033. * @return {number} X position of the pointer
  19034. */
  19035. get: function () {
  19036. return this._pointerX;
  19037. },
  19038. enumerable: true,
  19039. configurable: true
  19040. });
  19041. Object.defineProperty(Scene.prototype, "pointerY", {
  19042. /**
  19043. * Current on-screen Y position of the pointer
  19044. * @return {number} Y position of the pointer
  19045. */
  19046. get: function () {
  19047. return this._pointerY;
  19048. },
  19049. enumerable: true,
  19050. configurable: true
  19051. });
  19052. Scene.prototype.getCachedMaterial = function () {
  19053. return this._cachedMaterial;
  19054. };
  19055. Scene.prototype.getCachedEffect = function () {
  19056. return this._cachedEffect;
  19057. };
  19058. Scene.prototype.getCachedVisibility = function () {
  19059. return this._cachedVisibility;
  19060. };
  19061. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  19062. if (visibility === void 0) { visibility = 1; }
  19063. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  19064. };
  19065. Scene.prototype.getBoundingBoxRenderer = function () {
  19066. if (!this._boundingBoxRenderer) {
  19067. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  19068. }
  19069. return this._boundingBoxRenderer;
  19070. };
  19071. Scene.prototype.getOutlineRenderer = function () {
  19072. return this._outlineRenderer;
  19073. };
  19074. Scene.prototype.getEngine = function () {
  19075. return this._engine;
  19076. };
  19077. Scene.prototype.getTotalVertices = function () {
  19078. return this._totalVertices.current;
  19079. };
  19080. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  19081. get: function () {
  19082. return this._totalVertices;
  19083. },
  19084. enumerable: true,
  19085. configurable: true
  19086. });
  19087. Scene.prototype.getActiveIndices = function () {
  19088. return this._activeIndices.current;
  19089. };
  19090. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  19091. get: function () {
  19092. return this._activeIndices;
  19093. },
  19094. enumerable: true,
  19095. configurable: true
  19096. });
  19097. Scene.prototype.getActiveParticles = function () {
  19098. return this._activeParticles.current;
  19099. };
  19100. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  19101. get: function () {
  19102. return this._activeParticles;
  19103. },
  19104. enumerable: true,
  19105. configurable: true
  19106. });
  19107. Scene.prototype.getActiveBones = function () {
  19108. return this._activeBones.current;
  19109. };
  19110. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  19111. get: function () {
  19112. return this._activeBones;
  19113. },
  19114. enumerable: true,
  19115. configurable: true
  19116. });
  19117. // Stats
  19118. Scene.prototype.getInterFramePerfCounter = function () {
  19119. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  19120. return 0;
  19121. };
  19122. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  19123. get: function () {
  19124. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  19125. return null;
  19126. },
  19127. enumerable: true,
  19128. configurable: true
  19129. });
  19130. Scene.prototype.getLastFrameDuration = function () {
  19131. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  19132. return 0;
  19133. };
  19134. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  19135. get: function () {
  19136. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  19137. return null;
  19138. },
  19139. enumerable: true,
  19140. configurable: true
  19141. });
  19142. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  19143. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  19144. return 0;
  19145. };
  19146. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  19147. get: function () {
  19148. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  19149. return null;
  19150. },
  19151. enumerable: true,
  19152. configurable: true
  19153. });
  19154. Scene.prototype.getActiveMeshes = function () {
  19155. return this._activeMeshes;
  19156. };
  19157. Scene.prototype.getRenderTargetsDuration = function () {
  19158. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  19159. return 0;
  19160. };
  19161. Scene.prototype.getRenderDuration = function () {
  19162. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  19163. return 0;
  19164. };
  19165. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  19166. get: function () {
  19167. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  19168. return null;
  19169. },
  19170. enumerable: true,
  19171. configurable: true
  19172. });
  19173. Scene.prototype.getParticlesDuration = function () {
  19174. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  19175. return 0;
  19176. };
  19177. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  19178. get: function () {
  19179. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  19180. return null;
  19181. },
  19182. enumerable: true,
  19183. configurable: true
  19184. });
  19185. Scene.prototype.getSpritesDuration = function () {
  19186. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  19187. return 0;
  19188. };
  19189. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  19190. get: function () {
  19191. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  19192. return null;
  19193. },
  19194. enumerable: true,
  19195. configurable: true
  19196. });
  19197. Scene.prototype.getAnimationRatio = function () {
  19198. return this._animationRatio;
  19199. };
  19200. Scene.prototype.getRenderId = function () {
  19201. return this._renderId;
  19202. };
  19203. Scene.prototype.incrementRenderId = function () {
  19204. this._renderId++;
  19205. };
  19206. Scene.prototype._updatePointerPosition = function (evt) {
  19207. var canvasRect = this._engine.getRenderingCanvasClientRect();
  19208. if (!canvasRect) {
  19209. return;
  19210. }
  19211. this._pointerX = evt.clientX - canvasRect.left;
  19212. this._pointerY = evt.clientY - canvasRect.top;
  19213. this._unTranslatedPointerX = this._pointerX;
  19214. this._unTranslatedPointerY = this._pointerY;
  19215. };
  19216. Scene.prototype._createUbo = function () {
  19217. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  19218. this._sceneUbo.addUniform("viewProjection", 16);
  19219. this._sceneUbo.addUniform("view", 16);
  19220. };
  19221. Scene.prototype._createAlternateUbo = function () {
  19222. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  19223. this._alternateSceneUbo.addUniform("viewProjection", 16);
  19224. this._alternateSceneUbo.addUniform("view", 16);
  19225. };
  19226. // Pointers handling
  19227. /**
  19228. * Use this method to simulate a pointer move on a mesh
  19229. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  19230. */
  19231. Scene.prototype.simulatePointerMove = function (pickResult) {
  19232. var evt = new PointerEvent("pointermove");
  19233. return this._processPointerMove(pickResult, evt);
  19234. };
  19235. Scene.prototype._processPointerMove = function (pickResult, evt) {
  19236. var canvas = this._engine.getRenderingCanvas();
  19237. if (!canvas) {
  19238. return this;
  19239. }
  19240. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  19241. this.setPointerOverSprite(null);
  19242. this.setPointerOverMesh(pickResult.pickedMesh);
  19243. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  19244. if (this._pointerOverMesh.actionManager.hoverCursor) {
  19245. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  19246. }
  19247. else {
  19248. canvas.style.cursor = this.hoverCursor;
  19249. }
  19250. }
  19251. else {
  19252. canvas.style.cursor = this.defaultCursor;
  19253. }
  19254. }
  19255. else {
  19256. this.setPointerOverMesh(null);
  19257. // Sprites
  19258. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  19259. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  19260. this.setPointerOverSprite(pickResult.pickedSprite);
  19261. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  19262. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  19263. }
  19264. else {
  19265. canvas.style.cursor = this.hoverCursor;
  19266. }
  19267. }
  19268. else {
  19269. this.setPointerOverSprite(null);
  19270. // Restore pointer
  19271. canvas.style.cursor = this.defaultCursor;
  19272. }
  19273. }
  19274. if (pickResult) {
  19275. if (this.onPointerMove) {
  19276. this.onPointerMove(evt, pickResult);
  19277. }
  19278. if (this.onPointerObservable.hasObservers()) {
  19279. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  19280. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  19281. this.onPointerObservable.notifyObservers(pi, type);
  19282. }
  19283. }
  19284. return this;
  19285. };
  19286. /**
  19287. * Use this method to simulate a pointer down on a mesh
  19288. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  19289. */
  19290. Scene.prototype.simulatePointerDown = function (pickResult) {
  19291. var evt = new PointerEvent("pointerdown");
  19292. return this._processPointerDown(pickResult, evt);
  19293. };
  19294. Scene.prototype._processPointerDown = function (pickResult, evt) {
  19295. var _this = this;
  19296. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  19297. this._pickedDownMesh = pickResult.pickedMesh;
  19298. var actionManager = pickResult.pickedMesh.actionManager;
  19299. if (actionManager) {
  19300. if (actionManager.hasPickTriggers) {
  19301. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  19302. switch (evt.button) {
  19303. case 0:
  19304. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  19305. break;
  19306. case 1:
  19307. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  19308. break;
  19309. case 2:
  19310. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  19311. break;
  19312. }
  19313. }
  19314. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  19315. window.setTimeout(function () {
  19316. 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);
  19317. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  19318. if (_this._totalPointersPressed !== 0 &&
  19319. ((new Date().getTime() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  19320. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  19321. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  19322. _this._startingPointerTime = 0;
  19323. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  19324. }
  19325. }
  19326. }, Scene.LongPressDelay);
  19327. }
  19328. }
  19329. }
  19330. if (pickResult) {
  19331. if (this.onPointerDown) {
  19332. this.onPointerDown(evt, pickResult);
  19333. }
  19334. if (this.onPointerObservable.hasObservers()) {
  19335. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  19336. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  19337. this.onPointerObservable.notifyObservers(pi, type);
  19338. }
  19339. }
  19340. return this;
  19341. };
  19342. /**
  19343. * Use this method to simulate a pointer up on a mesh
  19344. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  19345. */
  19346. Scene.prototype.simulatePointerUp = function (pickResult) {
  19347. var evt = new PointerEvent("pointerup");
  19348. var clickInfo = new ClickInfo();
  19349. clickInfo.singleClick = true;
  19350. clickInfo.ignore = true;
  19351. return this._processPointerUp(pickResult, evt, clickInfo);
  19352. };
  19353. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  19354. if (pickResult && pickResult && pickResult.pickedMesh) {
  19355. this._pickedUpMesh = pickResult.pickedMesh;
  19356. if (this._pickedDownMesh === this._pickedUpMesh) {
  19357. if (this.onPointerPick) {
  19358. this.onPointerPick(evt, pickResult);
  19359. }
  19360. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  19361. var type = BABYLON.PointerEventTypes.POINTERPICK;
  19362. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  19363. this.onPointerObservable.notifyObservers(pi, type);
  19364. }
  19365. }
  19366. if (pickResult.pickedMesh.actionManager) {
  19367. if (clickInfo.ignore) {
  19368. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  19369. }
  19370. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  19371. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  19372. }
  19373. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  19374. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  19375. }
  19376. }
  19377. }
  19378. if (this._pickedDownMesh &&
  19379. this._pickedDownMesh.actionManager &&
  19380. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  19381. this._pickedDownMesh !== this._pickedUpMesh) {
  19382. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  19383. }
  19384. if (this.onPointerUp) {
  19385. this.onPointerUp(evt, pickResult);
  19386. }
  19387. if (this.onPointerObservable.hasObservers()) {
  19388. if (!clickInfo.ignore) {
  19389. if (!clickInfo.hasSwiped) {
  19390. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  19391. var type = BABYLON.PointerEventTypes.POINTERTAP;
  19392. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  19393. this.onPointerObservable.notifyObservers(pi, type);
  19394. }
  19395. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  19396. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  19397. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  19398. this.onPointerObservable.notifyObservers(pi, type);
  19399. }
  19400. }
  19401. }
  19402. else {
  19403. var type = BABYLON.PointerEventTypes.POINTERUP;
  19404. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  19405. this.onPointerObservable.notifyObservers(pi, type);
  19406. }
  19407. }
  19408. return this;
  19409. };
  19410. /**
  19411. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  19412. * @param attachUp defines if you want to attach events to pointerup
  19413. * @param attachDown defines if you want to attach events to pointerdown
  19414. * @param attachMove defines if you want to attach events to pointermove
  19415. */
  19416. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  19417. var _this = this;
  19418. if (attachUp === void 0) { attachUp = true; }
  19419. if (attachDown === void 0) { attachDown = true; }
  19420. if (attachMove === void 0) { attachMove = true; }
  19421. this._initActionManager = function (act, clickInfo) {
  19422. if (!_this._meshPickProceed) {
  19423. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  19424. _this._currentPickResult = pickResult;
  19425. if (pickResult) {
  19426. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  19427. }
  19428. _this._meshPickProceed = true;
  19429. }
  19430. return act;
  19431. };
  19432. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  19433. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  19434. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  19435. btn !== _this._previousButtonPressed) {
  19436. _this._doubleClickOccured = false;
  19437. clickInfo.singleClick = true;
  19438. clickInfo.ignore = false;
  19439. cb(clickInfo, _this._currentPickResult);
  19440. }
  19441. };
  19442. this._initClickEvent = function (obs1, obs2, evt, cb) {
  19443. var clickInfo = new ClickInfo();
  19444. _this._currentPickResult = null;
  19445. var act = null;
  19446. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  19447. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  19448. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  19449. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  19450. act = _this._initActionManager(act, clickInfo);
  19451. if (act)
  19452. checkPicking = act.hasPickTriggers;
  19453. }
  19454. if (checkPicking) {
  19455. var btn = evt.button;
  19456. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  19457. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  19458. if (!clickInfo.hasSwiped) {
  19459. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  19460. if (!checkSingleClickImmediately) {
  19461. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  19462. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  19463. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  19464. act = _this._initActionManager(act, clickInfo);
  19465. if (act)
  19466. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  19467. }
  19468. }
  19469. if (checkSingleClickImmediately) {
  19470. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  19471. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  19472. btn !== _this._previousButtonPressed) {
  19473. clickInfo.singleClick = true;
  19474. cb(clickInfo, _this._currentPickResult);
  19475. }
  19476. }
  19477. else {
  19478. // wait that no double click has been raised during the double click delay
  19479. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  19480. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  19481. }
  19482. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  19483. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  19484. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  19485. act = _this._initActionManager(act, clickInfo);
  19486. if (act)
  19487. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  19488. }
  19489. if (checkDoubleClick) {
  19490. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  19491. if (btn === _this._previousButtonPressed &&
  19492. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  19493. !_this._doubleClickOccured) {
  19494. // pointer has not moved for 2 clicks, it's a double click
  19495. if (!clickInfo.hasSwiped &&
  19496. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  19497. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  19498. _this._previousStartingPointerTime = 0;
  19499. _this._doubleClickOccured = true;
  19500. clickInfo.doubleClick = true;
  19501. clickInfo.ignore = false;
  19502. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  19503. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  19504. }
  19505. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  19506. cb(clickInfo, _this._currentPickResult);
  19507. }
  19508. else {
  19509. _this._doubleClickOccured = false;
  19510. _this._previousStartingPointerTime = _this._startingPointerTime;
  19511. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  19512. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  19513. _this._previousButtonPressed = btn;
  19514. if (Scene.ExclusiveDoubleClickMode) {
  19515. if (_this._previousDelayedSimpleClickTimeout) {
  19516. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  19517. }
  19518. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  19519. cb(clickInfo, _this._previousPickResult);
  19520. }
  19521. else {
  19522. cb(clickInfo, _this._currentPickResult);
  19523. }
  19524. }
  19525. }
  19526. else {
  19527. _this._doubleClickOccured = false;
  19528. _this._previousStartingPointerTime = _this._startingPointerTime;
  19529. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  19530. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  19531. _this._previousButtonPressed = btn;
  19532. }
  19533. }
  19534. }
  19535. }
  19536. clickInfo.ignore = true;
  19537. cb(clickInfo, _this._currentPickResult);
  19538. };
  19539. this._spritePredicate = function (sprite) {
  19540. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  19541. };
  19542. this._onPointerMove = function (evt) {
  19543. _this._updatePointerPosition(evt);
  19544. // PreObservable support
  19545. if (_this.onPrePointerObservable.hasObservers()) {
  19546. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  19547. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  19548. _this.onPrePointerObservable.notifyObservers(pi, type);
  19549. if (pi.skipOnPointerObservable) {
  19550. return;
  19551. }
  19552. }
  19553. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  19554. return;
  19555. }
  19556. if (!_this.pointerMovePredicate) {
  19557. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  19558. }
  19559. // Meshes
  19560. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  19561. _this._processPointerMove(pickResult, evt);
  19562. };
  19563. this._onPointerDown = function (evt) {
  19564. _this._totalPointersPressed++;
  19565. _this._pickedDownMesh = null;
  19566. _this._meshPickProceed = false;
  19567. _this._updatePointerPosition(evt);
  19568. if (_this.preventDefaultOnPointerDown && canvas) {
  19569. evt.preventDefault();
  19570. canvas.focus();
  19571. }
  19572. // PreObservable support
  19573. if (_this.onPrePointerObservable.hasObservers()) {
  19574. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  19575. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  19576. _this.onPrePointerObservable.notifyObservers(pi, type);
  19577. if (pi.skipOnPointerObservable) {
  19578. return;
  19579. }
  19580. }
  19581. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  19582. return;
  19583. }
  19584. _this._startingPointerPosition.x = _this._pointerX;
  19585. _this._startingPointerPosition.y = _this._pointerY;
  19586. _this._startingPointerTime = new Date().getTime();
  19587. if (!_this.pointerDownPredicate) {
  19588. _this.pointerDownPredicate = function (mesh) {
  19589. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  19590. };
  19591. }
  19592. // Meshes
  19593. _this._pickedDownMesh = null;
  19594. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  19595. _this._processPointerDown(pickResult, evt);
  19596. // Sprites
  19597. _this._pickedDownSprite = null;
  19598. if (_this.spriteManagers.length > 0) {
  19599. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  19600. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  19601. if (pickResult.pickedSprite.actionManager) {
  19602. _this._pickedDownSprite = pickResult.pickedSprite;
  19603. switch (evt.button) {
  19604. case 0:
  19605. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  19606. break;
  19607. case 1:
  19608. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  19609. break;
  19610. case 2:
  19611. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  19612. break;
  19613. }
  19614. if (pickResult.pickedSprite.actionManager) {
  19615. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  19616. }
  19617. }
  19618. }
  19619. }
  19620. };
  19621. this._onPointerUp = function (evt) {
  19622. if (_this._totalPointersPressed === 0) {
  19623. return; // So we need to test it the pointer down was pressed before.
  19624. }
  19625. _this._totalPointersPressed--;
  19626. _this._pickedUpMesh = null;
  19627. _this._meshPickProceed = false;
  19628. _this._updatePointerPosition(evt);
  19629. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  19630. // PreObservable support
  19631. if (_this.onPrePointerObservable.hasObservers()) {
  19632. if (!clickInfo.ignore) {
  19633. if (!clickInfo.hasSwiped) {
  19634. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  19635. var type = BABYLON.PointerEventTypes.POINTERTAP;
  19636. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  19637. _this.onPrePointerObservable.notifyObservers(pi, type);
  19638. if (pi.skipOnPointerObservable) {
  19639. return;
  19640. }
  19641. }
  19642. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  19643. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  19644. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  19645. _this.onPrePointerObservable.notifyObservers(pi, type);
  19646. if (pi.skipOnPointerObservable) {
  19647. return;
  19648. }
  19649. }
  19650. }
  19651. }
  19652. else {
  19653. var type = BABYLON.PointerEventTypes.POINTERUP;
  19654. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  19655. _this.onPrePointerObservable.notifyObservers(pi, type);
  19656. if (pi.skipOnPointerObservable) {
  19657. return;
  19658. }
  19659. }
  19660. }
  19661. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  19662. return;
  19663. }
  19664. if (!_this.pointerUpPredicate) {
  19665. _this.pointerUpPredicate = function (mesh) {
  19666. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  19667. };
  19668. }
  19669. // Meshes
  19670. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  19671. _this._initActionManager(null, clickInfo);
  19672. }
  19673. if (!pickResult) {
  19674. pickResult = _this._currentPickResult;
  19675. }
  19676. _this._processPointerUp(pickResult, evt, clickInfo);
  19677. // Sprites
  19678. if (_this.spriteManagers.length > 0) {
  19679. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  19680. if (spritePickResult) {
  19681. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  19682. if (spritePickResult.pickedSprite.actionManager) {
  19683. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  19684. if (spritePickResult.pickedSprite.actionManager) {
  19685. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  19686. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  19687. }
  19688. }
  19689. }
  19690. }
  19691. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  19692. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  19693. }
  19694. }
  19695. }
  19696. _this._previousPickResult = _this._currentPickResult;
  19697. });
  19698. };
  19699. this._onKeyDown = function (evt) {
  19700. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  19701. if (_this.onPreKeyboardObservable.hasObservers()) {
  19702. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  19703. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  19704. if (pi.skipOnPointerObservable) {
  19705. return;
  19706. }
  19707. }
  19708. if (_this.onKeyboardObservable.hasObservers()) {
  19709. var pi = new BABYLON.KeyboardInfo(type, evt);
  19710. _this.onKeyboardObservable.notifyObservers(pi, type);
  19711. }
  19712. if (_this.actionManager) {
  19713. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  19714. }
  19715. };
  19716. this._onKeyUp = function (evt) {
  19717. var type = BABYLON.KeyboardEventTypes.KEYUP;
  19718. if (_this.onPreKeyboardObservable.hasObservers()) {
  19719. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  19720. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  19721. if (pi.skipOnPointerObservable) {
  19722. return;
  19723. }
  19724. }
  19725. if (_this.onKeyboardObservable.hasObservers()) {
  19726. var pi = new BABYLON.KeyboardInfo(type, evt);
  19727. _this.onKeyboardObservable.notifyObservers(pi, type);
  19728. }
  19729. if (_this.actionManager) {
  19730. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  19731. }
  19732. };
  19733. var engine = this.getEngine();
  19734. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  19735. if (!canvas) {
  19736. return;
  19737. }
  19738. canvas.addEventListener("keydown", _this._onKeyDown, false);
  19739. canvas.addEventListener("keyup", _this._onKeyUp, false);
  19740. });
  19741. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  19742. if (!canvas) {
  19743. return;
  19744. }
  19745. canvas.removeEventListener("keydown", _this._onKeyDown);
  19746. canvas.removeEventListener("keyup", _this._onKeyUp);
  19747. });
  19748. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  19749. var canvas = this._engine.getRenderingCanvas();
  19750. if (!canvas) {
  19751. return;
  19752. }
  19753. if (attachMove) {
  19754. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  19755. // Wheel
  19756. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  19757. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  19758. }
  19759. if (attachDown) {
  19760. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  19761. }
  19762. if (attachUp) {
  19763. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  19764. }
  19765. canvas.tabIndex = 1;
  19766. };
  19767. Scene.prototype.detachControl = function () {
  19768. var engine = this.getEngine();
  19769. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  19770. var canvas = engine.getRenderingCanvas();
  19771. if (!canvas) {
  19772. return;
  19773. }
  19774. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  19775. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  19776. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  19777. if (this._onCanvasBlurObserver) {
  19778. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  19779. }
  19780. if (this._onCanvasFocusObserver) {
  19781. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  19782. }
  19783. // Wheel
  19784. canvas.removeEventListener('mousewheel', this._onPointerMove);
  19785. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  19786. // Keyboard
  19787. canvas.removeEventListener("keydown", this._onKeyDown);
  19788. canvas.removeEventListener("keyup", this._onKeyUp);
  19789. // Observables
  19790. this.onKeyboardObservable.clear();
  19791. this.onPreKeyboardObservable.clear();
  19792. this.onPointerObservable.clear();
  19793. this.onPrePointerObservable.clear();
  19794. };
  19795. // Ready
  19796. Scene.prototype.isReady = function () {
  19797. if (this._isDisposed) {
  19798. return false;
  19799. }
  19800. if (this._pendingData.length > 0) {
  19801. return false;
  19802. }
  19803. var index;
  19804. // Geometries
  19805. for (index = 0; index < this._geometries.length; index++) {
  19806. var geometry = this._geometries[index];
  19807. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  19808. return false;
  19809. }
  19810. }
  19811. // Meshes
  19812. for (index = 0; index < this.meshes.length; index++) {
  19813. var mesh = this.meshes[index];
  19814. if (!mesh.isEnabled()) {
  19815. continue;
  19816. }
  19817. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  19818. continue;
  19819. }
  19820. if (!mesh.isReady()) {
  19821. return false;
  19822. }
  19823. var mat = mesh.material;
  19824. if (mat) {
  19825. if (!mat.isReady(mesh)) {
  19826. return false;
  19827. }
  19828. }
  19829. }
  19830. return true;
  19831. };
  19832. Scene.prototype.resetCachedMaterial = function () {
  19833. this._cachedMaterial = null;
  19834. this._cachedEffect = null;
  19835. this._cachedVisibility = null;
  19836. };
  19837. Scene.prototype.registerBeforeRender = function (func) {
  19838. this.onBeforeRenderObservable.add(func);
  19839. };
  19840. Scene.prototype.unregisterBeforeRender = function (func) {
  19841. this.onBeforeRenderObservable.removeCallback(func);
  19842. };
  19843. Scene.prototype.registerAfterRender = function (func) {
  19844. this.onAfterRenderObservable.add(func);
  19845. };
  19846. Scene.prototype.unregisterAfterRender = function (func) {
  19847. this.onAfterRenderObservable.removeCallback(func);
  19848. };
  19849. Scene.prototype._addPendingData = function (data) {
  19850. this._pendingData.push(data);
  19851. };
  19852. Scene.prototype._removePendingData = function (data) {
  19853. var wasLoading = this.isLoading;
  19854. var index = this._pendingData.indexOf(data);
  19855. if (index !== -1) {
  19856. this._pendingData.splice(index, 1);
  19857. }
  19858. if (wasLoading && !this.isLoading) {
  19859. this.onDataLoadedObservable.notifyObservers(this);
  19860. }
  19861. };
  19862. Scene.prototype.getWaitingItemsCount = function () {
  19863. return this._pendingData.length;
  19864. };
  19865. Object.defineProperty(Scene.prototype, "isLoading", {
  19866. get: function () {
  19867. return this._pendingData.length > 0;
  19868. },
  19869. enumerable: true,
  19870. configurable: true
  19871. });
  19872. /**
  19873. * Registers a function to be executed when the scene is ready.
  19874. * @param {Function} func - the function to be executed.
  19875. */
  19876. Scene.prototype.executeWhenReady = function (func) {
  19877. var _this = this;
  19878. this.onReadyObservable.add(func);
  19879. if (this._executeWhenReadyTimeoutId !== -1) {
  19880. return;
  19881. }
  19882. this._executeWhenReadyTimeoutId = setTimeout(function () {
  19883. _this._checkIsReady();
  19884. }, 150);
  19885. };
  19886. Scene.prototype._checkIsReady = function () {
  19887. var _this = this;
  19888. if (this.isReady()) {
  19889. this.onReadyObservable.notifyObservers(this);
  19890. this.onReadyObservable.clear();
  19891. this._executeWhenReadyTimeoutId = -1;
  19892. return;
  19893. }
  19894. this._executeWhenReadyTimeoutId = setTimeout(function () {
  19895. _this._checkIsReady();
  19896. }, 150);
  19897. };
  19898. // Animations
  19899. /**
  19900. * Will start the animation sequence of a given target
  19901. * @param target - the target
  19902. * @param {number} from - from which frame should animation start
  19903. * @param {number} to - till which frame should animation run.
  19904. * @param {boolean} [loop] - should the animation loop
  19905. * @param {number} [speedRatio] - the speed in which to run the animation
  19906. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  19907. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  19908. * Returns {BABYLON.Animatable} the animatable object created for this animation
  19909. * See BABYLON.Animatable
  19910. */
  19911. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  19912. if (speedRatio === void 0) { speedRatio = 1.0; }
  19913. if (from > to && speedRatio > 0) {
  19914. speedRatio *= -1;
  19915. }
  19916. this.stopAnimation(target);
  19917. if (!animatable) {
  19918. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  19919. }
  19920. // Local animations
  19921. if (target.animations) {
  19922. animatable.appendAnimations(target, target.animations);
  19923. }
  19924. // Children animations
  19925. if (target.getAnimatables) {
  19926. var animatables = target.getAnimatables();
  19927. for (var index = 0; index < animatables.length; index++) {
  19928. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  19929. }
  19930. }
  19931. animatable.reset();
  19932. return animatable;
  19933. };
  19934. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  19935. if (speedRatio === undefined) {
  19936. speedRatio = 1.0;
  19937. }
  19938. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  19939. return animatable;
  19940. };
  19941. Scene.prototype.getAnimatableByTarget = function (target) {
  19942. for (var index = 0; index < this._activeAnimatables.length; index++) {
  19943. if (this._activeAnimatables[index].target === target) {
  19944. return this._activeAnimatables[index];
  19945. }
  19946. }
  19947. return null;
  19948. };
  19949. Object.defineProperty(Scene.prototype, "animatables", {
  19950. get: function () {
  19951. return this._activeAnimatables;
  19952. },
  19953. enumerable: true,
  19954. configurable: true
  19955. });
  19956. /**
  19957. * Will stop the animation of the given target
  19958. * @param target - the target
  19959. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  19960. * @see beginAnimation
  19961. */
  19962. Scene.prototype.stopAnimation = function (target, animationName) {
  19963. var animatable = this.getAnimatableByTarget(target);
  19964. if (animatable) {
  19965. animatable.stop(animationName);
  19966. }
  19967. };
  19968. /**
  19969. * Stops and removes all animations that have been applied to the scene
  19970. */
  19971. Scene.prototype.stopAllAnimations = function () {
  19972. if (this._activeAnimatables) {
  19973. for (var i = 0; i < this._activeAnimatables.length; i++) {
  19974. this._activeAnimatables[i].stop();
  19975. }
  19976. this._activeAnimatables = [];
  19977. }
  19978. };
  19979. Scene.prototype._animate = function () {
  19980. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  19981. return;
  19982. }
  19983. // Getting time
  19984. var now = BABYLON.Tools.Now;
  19985. if (!this._animationTimeLast) {
  19986. if (this._pendingData.length > 0) {
  19987. return;
  19988. }
  19989. this._animationTimeLast = now;
  19990. }
  19991. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  19992. this._animationTime += deltaTime;
  19993. this._animationTimeLast = now;
  19994. for (var index = 0; index < this._activeAnimatables.length; index++) {
  19995. this._activeAnimatables[index]._animate(this._animationTime);
  19996. }
  19997. };
  19998. // Matrix
  19999. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  20000. this._useAlternateCameraConfiguration = active;
  20001. };
  20002. Scene.prototype.getViewMatrix = function () {
  20003. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  20004. };
  20005. Scene.prototype.getProjectionMatrix = function () {
  20006. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  20007. };
  20008. Scene.prototype.getTransformMatrix = function () {
  20009. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  20010. };
  20011. Scene.prototype.setTransformMatrix = function (view, projection) {
  20012. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  20013. return;
  20014. }
  20015. this._viewUpdateFlag = view.updateFlag;
  20016. this._projectionUpdateFlag = projection.updateFlag;
  20017. this._viewMatrix = view;
  20018. this._projectionMatrix = projection;
  20019. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  20020. // Update frustum
  20021. if (!this._frustumPlanes) {
  20022. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  20023. }
  20024. else {
  20025. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  20026. }
  20027. if (this.activeCamera && this.activeCamera._alternateCamera) {
  20028. var otherCamera = this.activeCamera._alternateCamera;
  20029. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  20030. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  20031. }
  20032. if (this._sceneUbo.useUbo) {
  20033. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  20034. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  20035. this._sceneUbo.update();
  20036. }
  20037. };
  20038. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  20039. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  20040. return;
  20041. }
  20042. this._alternateViewUpdateFlag = view.updateFlag;
  20043. this._alternateProjectionUpdateFlag = projection.updateFlag;
  20044. this._alternateViewMatrix = view;
  20045. this._alternateProjectionMatrix = projection;
  20046. if (!this._alternateTransformMatrix) {
  20047. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  20048. }
  20049. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  20050. if (!this._alternateSceneUbo) {
  20051. this._createAlternateUbo();
  20052. }
  20053. if (this._alternateSceneUbo.useUbo) {
  20054. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  20055. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  20056. this._alternateSceneUbo.update();
  20057. }
  20058. };
  20059. Scene.prototype.getSceneUniformBuffer = function () {
  20060. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  20061. };
  20062. // Methods
  20063. Scene.prototype.getUniqueId = function () {
  20064. var result = Scene._uniqueIdCounter;
  20065. Scene._uniqueIdCounter++;
  20066. return result;
  20067. };
  20068. Scene.prototype.addMesh = function (newMesh) {
  20069. this.meshes.push(newMesh);
  20070. //notify the collision coordinator
  20071. if (this.collisionCoordinator) {
  20072. this.collisionCoordinator.onMeshAdded(newMesh);
  20073. }
  20074. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  20075. };
  20076. Scene.prototype.removeMesh = function (toRemove) {
  20077. var index = this.meshes.indexOf(toRemove);
  20078. if (index !== -1) {
  20079. // Remove from the scene if mesh found
  20080. this.meshes.splice(index, 1);
  20081. }
  20082. this.onMeshRemovedObservable.notifyObservers(toRemove);
  20083. return index;
  20084. };
  20085. Scene.prototype.addTransformNode = function (newTransformNode) {
  20086. this.transformNodes.push(newTransformNode);
  20087. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  20088. };
  20089. Scene.prototype.removeTransformNode = function (toRemove) {
  20090. var index = this.transformNodes.indexOf(toRemove);
  20091. if (index !== -1) {
  20092. // Remove from the scene if found
  20093. this.transformNodes.splice(index, 1);
  20094. }
  20095. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  20096. return index;
  20097. };
  20098. Scene.prototype.removeSkeleton = function (toRemove) {
  20099. var index = this.skeletons.indexOf(toRemove);
  20100. if (index !== -1) {
  20101. // Remove from the scene if found
  20102. this.skeletons.splice(index, 1);
  20103. }
  20104. return index;
  20105. };
  20106. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  20107. var index = this.morphTargetManagers.indexOf(toRemove);
  20108. if (index !== -1) {
  20109. // Remove from the scene if found
  20110. this.morphTargetManagers.splice(index, 1);
  20111. }
  20112. return index;
  20113. };
  20114. Scene.prototype.removeLight = function (toRemove) {
  20115. var index = this.lights.indexOf(toRemove);
  20116. if (index !== -1) {
  20117. // Remove from the scene if mesh found
  20118. this.lights.splice(index, 1);
  20119. this.sortLightsByPriority();
  20120. }
  20121. this.onLightRemovedObservable.notifyObservers(toRemove);
  20122. return index;
  20123. };
  20124. Scene.prototype.removeCamera = function (toRemove) {
  20125. var index = this.cameras.indexOf(toRemove);
  20126. if (index !== -1) {
  20127. // Remove from the scene if mesh found
  20128. this.cameras.splice(index, 1);
  20129. }
  20130. // Remove from activeCameras
  20131. var index2 = this.activeCameras.indexOf(toRemove);
  20132. if (index2 !== -1) {
  20133. // Remove from the scene if mesh found
  20134. this.activeCameras.splice(index2, 1);
  20135. }
  20136. // Reset the activeCamera
  20137. if (this.activeCamera === toRemove) {
  20138. if (this.cameras.length > 0) {
  20139. this.activeCamera = this.cameras[0];
  20140. }
  20141. else {
  20142. this.activeCamera = null;
  20143. }
  20144. }
  20145. this.onCameraRemovedObservable.notifyObservers(toRemove);
  20146. return index;
  20147. };
  20148. Scene.prototype.addLight = function (newLight) {
  20149. this.lights.push(newLight);
  20150. this.sortLightsByPriority();
  20151. this.onNewLightAddedObservable.notifyObservers(newLight);
  20152. };
  20153. Scene.prototype.sortLightsByPriority = function () {
  20154. if (this.requireLightSorting) {
  20155. this.lights.sort(BABYLON.Light.compareLightsPriority);
  20156. }
  20157. };
  20158. Scene.prototype.addCamera = function (newCamera) {
  20159. this.cameras.push(newCamera);
  20160. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  20161. };
  20162. /**
  20163. * Switch active camera
  20164. * @param {Camera} newCamera - new active camera
  20165. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  20166. */
  20167. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  20168. if (attachControl === void 0) { attachControl = true; }
  20169. var canvas = this._engine.getRenderingCanvas();
  20170. if (!canvas) {
  20171. return;
  20172. }
  20173. if (this.activeCamera) {
  20174. this.activeCamera.detachControl(canvas);
  20175. }
  20176. this.activeCamera = newCamera;
  20177. if (attachControl) {
  20178. newCamera.attachControl(canvas);
  20179. }
  20180. };
  20181. /**
  20182. * sets the active camera of the scene using its ID
  20183. * @param {string} id - the camera's ID
  20184. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  20185. * @see activeCamera
  20186. */
  20187. Scene.prototype.setActiveCameraByID = function (id) {
  20188. var camera = this.getCameraByID(id);
  20189. if (camera) {
  20190. this.activeCamera = camera;
  20191. return camera;
  20192. }
  20193. return null;
  20194. };
  20195. /**
  20196. * sets the active camera of the scene using its name
  20197. * @param {string} name - the camera's name
  20198. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  20199. * @see activeCamera
  20200. */
  20201. Scene.prototype.setActiveCameraByName = function (name) {
  20202. var camera = this.getCameraByName(name);
  20203. if (camera) {
  20204. this.activeCamera = camera;
  20205. return camera;
  20206. }
  20207. return null;
  20208. };
  20209. /**
  20210. * get an animation group using its name
  20211. * @param {string} the material's name
  20212. * @return {BABYLON.AnimationGroup|null} the animation group or null if none found.
  20213. */
  20214. Scene.prototype.getAnimationGroupByName = function (name) {
  20215. for (var index = 0; index < this.animationGroups.length; index++) {
  20216. if (this.animationGroups[index].name === name) {
  20217. return this.animationGroups[index];
  20218. }
  20219. }
  20220. return null;
  20221. };
  20222. /**
  20223. * get a material using its id
  20224. * @param {string} the material's ID
  20225. * @return {BABYLON.Material|null} the material or null if none found.
  20226. */
  20227. Scene.prototype.getMaterialByID = function (id) {
  20228. for (var index = 0; index < this.materials.length; index++) {
  20229. if (this.materials[index].id === id) {
  20230. return this.materials[index];
  20231. }
  20232. }
  20233. return null;
  20234. };
  20235. /**
  20236. * get a material using its name
  20237. * @param {string} the material's name
  20238. * @return {BABYLON.Material|null} the material or null if none found.
  20239. */
  20240. Scene.prototype.getMaterialByName = function (name) {
  20241. for (var index = 0; index < this.materials.length; index++) {
  20242. if (this.materials[index].name === name) {
  20243. return this.materials[index];
  20244. }
  20245. }
  20246. return null;
  20247. };
  20248. Scene.prototype.getLensFlareSystemByName = function (name) {
  20249. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  20250. if (this.lensFlareSystems[index].name === name) {
  20251. return this.lensFlareSystems[index];
  20252. }
  20253. }
  20254. return null;
  20255. };
  20256. Scene.prototype.getLensFlareSystemByID = function (id) {
  20257. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  20258. if (this.lensFlareSystems[index].id === id) {
  20259. return this.lensFlareSystems[index];
  20260. }
  20261. }
  20262. return null;
  20263. };
  20264. Scene.prototype.getCameraByID = function (id) {
  20265. for (var index = 0; index < this.cameras.length; index++) {
  20266. if (this.cameras[index].id === id) {
  20267. return this.cameras[index];
  20268. }
  20269. }
  20270. return null;
  20271. };
  20272. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  20273. for (var index = 0; index < this.cameras.length; index++) {
  20274. if (this.cameras[index].uniqueId === uniqueId) {
  20275. return this.cameras[index];
  20276. }
  20277. }
  20278. return null;
  20279. };
  20280. /**
  20281. * get a camera using its name
  20282. * @param {string} the camera's name
  20283. * @return {BABYLON.Camera|null} the camera or null if none found.
  20284. */
  20285. Scene.prototype.getCameraByName = function (name) {
  20286. for (var index = 0; index < this.cameras.length; index++) {
  20287. if (this.cameras[index].name === name) {
  20288. return this.cameras[index];
  20289. }
  20290. }
  20291. return null;
  20292. };
  20293. /**
  20294. * get a bone using its id
  20295. * @param {string} the bone's id
  20296. * @return {BABYLON.Bone|null} the bone or null if not found
  20297. */
  20298. Scene.prototype.getBoneByID = function (id) {
  20299. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  20300. var skeleton = this.skeletons[skeletonIndex];
  20301. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  20302. if (skeleton.bones[boneIndex].id === id) {
  20303. return skeleton.bones[boneIndex];
  20304. }
  20305. }
  20306. }
  20307. return null;
  20308. };
  20309. /**
  20310. * get a bone using its id
  20311. * @param {string} the bone's name
  20312. * @return {BABYLON.Bone|null} the bone or null if not found
  20313. */
  20314. Scene.prototype.getBoneByName = function (name) {
  20315. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  20316. var skeleton = this.skeletons[skeletonIndex];
  20317. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  20318. if (skeleton.bones[boneIndex].name === name) {
  20319. return skeleton.bones[boneIndex];
  20320. }
  20321. }
  20322. }
  20323. return null;
  20324. };
  20325. /**
  20326. * get a light node using its name
  20327. * @param {string} the light's name
  20328. * @return {BABYLON.Light|null} the light or null if none found.
  20329. */
  20330. Scene.prototype.getLightByName = function (name) {
  20331. for (var index = 0; index < this.lights.length; index++) {
  20332. if (this.lights[index].name === name) {
  20333. return this.lights[index];
  20334. }
  20335. }
  20336. return null;
  20337. };
  20338. /**
  20339. * get a light node using its ID
  20340. * @param {string} the light's id
  20341. * @return {BABYLON.Light|null} the light or null if none found.
  20342. */
  20343. Scene.prototype.getLightByID = function (id) {
  20344. for (var index = 0; index < this.lights.length; index++) {
  20345. if (this.lights[index].id === id) {
  20346. return this.lights[index];
  20347. }
  20348. }
  20349. return null;
  20350. };
  20351. /**
  20352. * get a light node using its scene-generated unique ID
  20353. * @param {number} the light's unique id
  20354. * @return {BABYLON.Light|null} the light or null if none found.
  20355. */
  20356. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  20357. for (var index = 0; index < this.lights.length; index++) {
  20358. if (this.lights[index].uniqueId === uniqueId) {
  20359. return this.lights[index];
  20360. }
  20361. }
  20362. return null;
  20363. };
  20364. /**
  20365. * get a particle system by id
  20366. * @param id {number} the particle system id
  20367. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  20368. */
  20369. Scene.prototype.getParticleSystemByID = function (id) {
  20370. for (var index = 0; index < this.particleSystems.length; index++) {
  20371. if (this.particleSystems[index].id === id) {
  20372. return this.particleSystems[index];
  20373. }
  20374. }
  20375. return null;
  20376. };
  20377. /**
  20378. * get a geometry using its ID
  20379. * @param {string} the geometry's id
  20380. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  20381. */
  20382. Scene.prototype.getGeometryByID = function (id) {
  20383. for (var index = 0; index < this._geometries.length; index++) {
  20384. if (this._geometries[index].id === id) {
  20385. return this._geometries[index];
  20386. }
  20387. }
  20388. return null;
  20389. };
  20390. /**
  20391. * add a new geometry to this scene.
  20392. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  20393. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  20394. * @return {boolean} was the geometry added or not
  20395. */
  20396. Scene.prototype.pushGeometry = function (geometry, force) {
  20397. if (!force && this.getGeometryByID(geometry.id)) {
  20398. return false;
  20399. }
  20400. this._geometries.push(geometry);
  20401. //notify the collision coordinator
  20402. if (this.collisionCoordinator) {
  20403. this.collisionCoordinator.onGeometryAdded(geometry);
  20404. }
  20405. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  20406. return true;
  20407. };
  20408. /**
  20409. * Removes an existing geometry
  20410. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  20411. * @return {boolean} was the geometry removed or not
  20412. */
  20413. Scene.prototype.removeGeometry = function (geometry) {
  20414. var index = this._geometries.indexOf(geometry);
  20415. if (index > -1) {
  20416. this._geometries.splice(index, 1);
  20417. //notify the collision coordinator
  20418. if (this.collisionCoordinator) {
  20419. this.collisionCoordinator.onGeometryDeleted(geometry);
  20420. }
  20421. this.onGeometryRemovedObservable.notifyObservers(geometry);
  20422. return true;
  20423. }
  20424. return false;
  20425. };
  20426. Scene.prototype.getGeometries = function () {
  20427. return this._geometries;
  20428. };
  20429. /**
  20430. * Get the first added mesh found of a given ID
  20431. * @param {string} id - the id to search for
  20432. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  20433. */
  20434. Scene.prototype.getMeshByID = function (id) {
  20435. for (var index = 0; index < this.meshes.length; index++) {
  20436. if (this.meshes[index].id === id) {
  20437. return this.meshes[index];
  20438. }
  20439. }
  20440. return null;
  20441. };
  20442. Scene.prototype.getMeshesByID = function (id) {
  20443. return this.meshes.filter(function (m) {
  20444. return m.id === id;
  20445. });
  20446. };
  20447. /**
  20448. * Get the first added transform node found of a given ID
  20449. * @param {string} id - the id to search for
  20450. * @return {BABYLON.TransformNode|null} the transform node found or null if not found at all.
  20451. */
  20452. Scene.prototype.getTransformNodeByID = function (id) {
  20453. for (var index = 0; index < this.transformNodes.length; index++) {
  20454. if (this.transformNodes[index].id === id) {
  20455. return this.transformNodes[index];
  20456. }
  20457. }
  20458. return null;
  20459. };
  20460. Scene.prototype.getTransformNodesByID = function (id) {
  20461. return this.transformNodes.filter(function (m) {
  20462. return m.id === id;
  20463. });
  20464. };
  20465. /**
  20466. * Get a mesh with its auto-generated unique id
  20467. * @param {number} uniqueId - the unique id to search for
  20468. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  20469. */
  20470. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  20471. for (var index = 0; index < this.meshes.length; index++) {
  20472. if (this.meshes[index].uniqueId === uniqueId) {
  20473. return this.meshes[index];
  20474. }
  20475. }
  20476. return null;
  20477. };
  20478. /**
  20479. * Get a the last added mesh found of a given ID
  20480. * @param {string} id - the id to search for
  20481. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  20482. */
  20483. Scene.prototype.getLastMeshByID = function (id) {
  20484. for (var index = this.meshes.length - 1; index >= 0; index--) {
  20485. if (this.meshes[index].id === id) {
  20486. return this.meshes[index];
  20487. }
  20488. }
  20489. return null;
  20490. };
  20491. /**
  20492. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  20493. * @param {string} id - the id to search for
  20494. * @return {BABYLON.Node|null} the node found or null if not found at all.
  20495. */
  20496. Scene.prototype.getLastEntryByID = function (id) {
  20497. var index;
  20498. for (index = this.meshes.length - 1; index >= 0; index--) {
  20499. if (this.meshes[index].id === id) {
  20500. return this.meshes[index];
  20501. }
  20502. }
  20503. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  20504. if (this.transformNodes[index].id === id) {
  20505. return this.transformNodes[index];
  20506. }
  20507. }
  20508. for (index = this.cameras.length - 1; index >= 0; index--) {
  20509. if (this.cameras[index].id === id) {
  20510. return this.cameras[index];
  20511. }
  20512. }
  20513. for (index = this.lights.length - 1; index >= 0; index--) {
  20514. if (this.lights[index].id === id) {
  20515. return this.lights[index];
  20516. }
  20517. }
  20518. return null;
  20519. };
  20520. Scene.prototype.getNodeByID = function (id) {
  20521. var mesh = this.getMeshByID(id);
  20522. if (mesh) {
  20523. return mesh;
  20524. }
  20525. var light = this.getLightByID(id);
  20526. if (light) {
  20527. return light;
  20528. }
  20529. var camera = this.getCameraByID(id);
  20530. if (camera) {
  20531. return camera;
  20532. }
  20533. var bone = this.getBoneByID(id);
  20534. return bone;
  20535. };
  20536. Scene.prototype.getNodeByName = function (name) {
  20537. var mesh = this.getMeshByName(name);
  20538. if (mesh) {
  20539. return mesh;
  20540. }
  20541. var light = this.getLightByName(name);
  20542. if (light) {
  20543. return light;
  20544. }
  20545. var camera = this.getCameraByName(name);
  20546. if (camera) {
  20547. return camera;
  20548. }
  20549. var bone = this.getBoneByName(name);
  20550. return bone;
  20551. };
  20552. Scene.prototype.getMeshByName = function (name) {
  20553. for (var index = 0; index < this.meshes.length; index++) {
  20554. if (this.meshes[index].name === name) {
  20555. return this.meshes[index];
  20556. }
  20557. }
  20558. return null;
  20559. };
  20560. Scene.prototype.getTransformNodeByName = function (name) {
  20561. for (var index = 0; index < this.transformNodes.length; index++) {
  20562. if (this.transformNodes[index].name === name) {
  20563. return this.transformNodes[index];
  20564. }
  20565. }
  20566. return null;
  20567. };
  20568. Scene.prototype.getSoundByName = function (name) {
  20569. var index;
  20570. if (BABYLON.AudioEngine) {
  20571. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  20572. if (this.mainSoundTrack.soundCollection[index].name === name) {
  20573. return this.mainSoundTrack.soundCollection[index];
  20574. }
  20575. }
  20576. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  20577. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  20578. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  20579. return this.soundTracks[sdIndex].soundCollection[index];
  20580. }
  20581. }
  20582. }
  20583. }
  20584. return null;
  20585. };
  20586. Scene.prototype.getLastSkeletonByID = function (id) {
  20587. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  20588. if (this.skeletons[index].id === id) {
  20589. return this.skeletons[index];
  20590. }
  20591. }
  20592. return null;
  20593. };
  20594. Scene.prototype.getSkeletonById = function (id) {
  20595. for (var index = 0; index < this.skeletons.length; index++) {
  20596. if (this.skeletons[index].id === id) {
  20597. return this.skeletons[index];
  20598. }
  20599. }
  20600. return null;
  20601. };
  20602. Scene.prototype.getSkeletonByName = function (name) {
  20603. for (var index = 0; index < this.skeletons.length; index++) {
  20604. if (this.skeletons[index].name === name) {
  20605. return this.skeletons[index];
  20606. }
  20607. }
  20608. return null;
  20609. };
  20610. Scene.prototype.getMorphTargetManagerById = function (id) {
  20611. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  20612. if (this.morphTargetManagers[index].uniqueId === id) {
  20613. return this.morphTargetManagers[index];
  20614. }
  20615. }
  20616. return null;
  20617. };
  20618. Scene.prototype.isActiveMesh = function (mesh) {
  20619. return (this._activeMeshes.indexOf(mesh) !== -1);
  20620. };
  20621. /**
  20622. * Return a the first highlight layer of the scene with a given name.
  20623. * @param name The name of the highlight layer to look for.
  20624. * @return The highlight layer if found otherwise null.
  20625. */
  20626. Scene.prototype.getHighlightLayerByName = function (name) {
  20627. for (var index = 0; index < this.highlightLayers.length; index++) {
  20628. if (this.highlightLayers[index].name === name) {
  20629. return this.highlightLayers[index];
  20630. }
  20631. }
  20632. return null;
  20633. };
  20634. Object.defineProperty(Scene.prototype, "uid", {
  20635. /**
  20636. * Return a unique id as a string which can serve as an identifier for the scene
  20637. */
  20638. get: function () {
  20639. if (!this._uid) {
  20640. this._uid = BABYLON.Tools.RandomId();
  20641. }
  20642. return this._uid;
  20643. },
  20644. enumerable: true,
  20645. configurable: true
  20646. });
  20647. /**
  20648. * Add an externaly attached data from its key.
  20649. * This method call will fail and return false, if such key already exists.
  20650. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  20651. * @param key the unique key that identifies the data
  20652. * @param data the data object to associate to the key for this Engine instance
  20653. * @return true if no such key were already present and the data was added successfully, false otherwise
  20654. */
  20655. Scene.prototype.addExternalData = function (key, data) {
  20656. if (!this._externalData) {
  20657. this._externalData = new BABYLON.StringDictionary();
  20658. }
  20659. return this._externalData.add(key, data);
  20660. };
  20661. /**
  20662. * Get an externaly attached data from its key
  20663. * @param key the unique key that identifies the data
  20664. * @return the associated data, if present (can be null), or undefined if not present
  20665. */
  20666. Scene.prototype.getExternalData = function (key) {
  20667. if (!this._externalData) {
  20668. return null;
  20669. }
  20670. return this._externalData.get(key);
  20671. };
  20672. /**
  20673. * Get an externaly attached data from its key, create it using a factory if it's not already present
  20674. * @param key the unique key that identifies the data
  20675. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  20676. * @return the associated data, can be null if the factory returned null.
  20677. */
  20678. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  20679. if (!this._externalData) {
  20680. this._externalData = new BABYLON.StringDictionary();
  20681. }
  20682. return this._externalData.getOrAddWithFactory(key, factory);
  20683. };
  20684. /**
  20685. * Remove an externaly attached data from the Engine instance
  20686. * @param key the unique key that identifies the data
  20687. * @return true if the data was successfully removed, false if it doesn't exist
  20688. */
  20689. Scene.prototype.removeExternalData = function (key) {
  20690. return this._externalData.remove(key);
  20691. };
  20692. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  20693. if (this.dispatchAllSubMeshesOfActiveMeshes === true || mesh.alwaysSelectAsActiveMesh === true || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  20694. if (mesh.showSubMeshesBoundingBox === true) {
  20695. var boundingInfo = subMesh.getBoundingInfo();
  20696. if (boundingInfo !== null && boundingInfo !== undefined) {
  20697. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  20698. }
  20699. }
  20700. var material = subMesh.getMaterial();
  20701. if (material !== null && material !== undefined) {
  20702. // Render targets
  20703. if (material.getRenderTargetTextures !== undefined) {
  20704. if (this._processedMaterials.indexOf(material) === -1) {
  20705. this._processedMaterials.push(material);
  20706. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  20707. }
  20708. }
  20709. // Dispatch
  20710. this._activeIndices.addCount(subMesh.indexCount, false);
  20711. this._renderingManager.dispatch(subMesh, mesh, material);
  20712. }
  20713. }
  20714. };
  20715. Scene.prototype._isInIntermediateRendering = function () {
  20716. return this._intermediateRendering;
  20717. };
  20718. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  20719. this._activeMeshCandidateProvider = provider;
  20720. };
  20721. Scene.prototype.getActiveMeshCandidateProvider = function () {
  20722. return this._activeMeshCandidateProvider;
  20723. };
  20724. /**
  20725. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  20726. */
  20727. Scene.prototype.freezeActiveMeshes = function () {
  20728. this._evaluateActiveMeshes();
  20729. this._activeMeshesFrozen = true;
  20730. return this;
  20731. };
  20732. /**
  20733. * Use this function to restart evaluating active meshes on every frame
  20734. */
  20735. Scene.prototype.unfreezeActiveMeshes = function () {
  20736. this._activeMeshesFrozen = false;
  20737. return this;
  20738. };
  20739. Scene.prototype._evaluateActiveMeshes = function () {
  20740. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  20741. return;
  20742. }
  20743. if (!this.activeCamera) {
  20744. return;
  20745. }
  20746. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  20747. this.activeCamera._activeMeshes.reset();
  20748. this._activeMeshes.reset();
  20749. this._renderingManager.reset();
  20750. this._processedMaterials.reset();
  20751. this._activeParticleSystems.reset();
  20752. this._activeSkeletons.reset();
  20753. this._softwareSkinnedMeshes.reset();
  20754. if (this._boundingBoxRenderer) {
  20755. this._boundingBoxRenderer.reset();
  20756. }
  20757. // Meshes
  20758. var meshes;
  20759. var len;
  20760. var checkIsEnabled = true;
  20761. // Determine mesh candidates
  20762. if (this._activeMeshCandidateProvider !== undefined) {
  20763. // Use _activeMeshCandidateProvider
  20764. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  20765. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  20766. if (meshes !== undefined) {
  20767. len = meshes.length;
  20768. }
  20769. else {
  20770. len = 0;
  20771. }
  20772. }
  20773. else if (this._selectionOctree !== undefined) {
  20774. // Octree
  20775. var selection = this._selectionOctree.select(this._frustumPlanes);
  20776. meshes = selection.data;
  20777. len = selection.length;
  20778. }
  20779. else {
  20780. // Full scene traversal
  20781. len = this.meshes.length;
  20782. meshes = this.meshes;
  20783. }
  20784. // Check each mesh
  20785. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  20786. mesh = meshes[meshIndex];
  20787. if (mesh.isBlocked === true) {
  20788. continue;
  20789. }
  20790. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  20791. if (mesh.isReady() === false || (checkIsEnabled === true && mesh.isEnabled() === false)) {
  20792. continue;
  20793. }
  20794. mesh.computeWorldMatrix();
  20795. // Intersections
  20796. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  20797. this._meshesForIntersections.pushNoDuplicate(mesh);
  20798. }
  20799. // Switch to current LOD
  20800. meshLOD = mesh.getLOD(this.activeCamera);
  20801. if (meshLOD === undefined || meshLOD === null) {
  20802. continue;
  20803. }
  20804. mesh._preActivate();
  20805. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  20806. this._activeMeshes.push(mesh);
  20807. this.activeCamera._activeMeshes.push(mesh);
  20808. mesh._activate(this._renderId);
  20809. if (meshLOD !== mesh) {
  20810. meshLOD._activate(this._renderId);
  20811. }
  20812. this._activeMesh(mesh, meshLOD);
  20813. }
  20814. }
  20815. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  20816. // Particle systems
  20817. if (this.particlesEnabled) {
  20818. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  20819. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  20820. var particleSystem = this.particleSystems[particleIndex];
  20821. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  20822. continue;
  20823. }
  20824. var emitter = particleSystem.emitter;
  20825. if (!emitter.position || emitter.isEnabled()) {
  20826. this._activeParticleSystems.push(particleSystem);
  20827. particleSystem.animate();
  20828. this._renderingManager.dispatchParticles(particleSystem);
  20829. }
  20830. }
  20831. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  20832. }
  20833. };
  20834. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  20835. if (this.skeletonsEnabled === true && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  20836. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  20837. mesh.skeleton.prepare();
  20838. }
  20839. if (!mesh.computeBonesUsingShaders) {
  20840. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  20841. }
  20842. }
  20843. if (sourceMesh.showBoundingBox === true || this.forceShowBoundingBoxes === true) {
  20844. var boundingInfo = sourceMesh.getBoundingInfo();
  20845. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  20846. }
  20847. if (mesh !== undefined && mesh !== null
  20848. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  20849. // Submeshes Octrees
  20850. var len;
  20851. var subMeshes;
  20852. if (mesh.useOctreeForRenderingSelection === true && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  20853. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  20854. len = intersections.length;
  20855. subMeshes = intersections.data;
  20856. }
  20857. else {
  20858. subMeshes = mesh.subMeshes;
  20859. len = subMeshes.length;
  20860. }
  20861. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  20862. subMesh = subMeshes[subIndex];
  20863. this._evaluateSubMesh(subMesh, mesh);
  20864. }
  20865. }
  20866. };
  20867. Scene.prototype.updateTransformMatrix = function (force) {
  20868. if (!this.activeCamera) {
  20869. return;
  20870. }
  20871. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  20872. };
  20873. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  20874. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  20875. };
  20876. Scene.prototype._renderForCamera = function (camera) {
  20877. if (camera && camera._skipRendering) {
  20878. return;
  20879. }
  20880. var engine = this._engine;
  20881. this.activeCamera = camera;
  20882. if (!this.activeCamera)
  20883. throw new Error("Active camera not set");
  20884. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  20885. // Viewport
  20886. engine.setViewport(this.activeCamera.viewport);
  20887. // Camera
  20888. this.resetCachedMaterial();
  20889. this._renderId++;
  20890. this.activeCamera.update();
  20891. this.updateTransformMatrix();
  20892. if (camera._alternateCamera) {
  20893. this.updateAlternateTransformMatrix(camera._alternateCamera);
  20894. this._alternateRendering = true;
  20895. }
  20896. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  20897. // Meshes
  20898. this._evaluateActiveMeshes();
  20899. // Software skinning
  20900. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  20901. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  20902. mesh.applySkeleton(mesh.skeleton);
  20903. }
  20904. // Render targets
  20905. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  20906. var needsRestoreFrameBuffer = false;
  20907. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  20908. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  20909. }
  20910. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  20911. this._intermediateRendering = true;
  20912. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  20913. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  20914. var renderTarget = this._renderTargets.data[renderIndex];
  20915. if (renderTarget._shouldRender()) {
  20916. this._renderId++;
  20917. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  20918. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  20919. }
  20920. }
  20921. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  20922. this._intermediateRendering = false;
  20923. this._renderId++;
  20924. needsRestoreFrameBuffer = true; // Restore back buffer
  20925. }
  20926. // Render HighlightLayer Texture
  20927. var stencilState = this._engine.getStencilBuffer();
  20928. var renderhighlights = false;
  20929. if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
  20930. this._intermediateRendering = true;
  20931. for (var i = 0; i < this.highlightLayers.length; i++) {
  20932. var highlightLayer = this.highlightLayers[i];
  20933. if (highlightLayer.shouldRender() &&
  20934. (!highlightLayer.camera ||
  20935. (highlightLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
  20936. (highlightLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
  20937. renderhighlights = true;
  20938. var renderTarget = highlightLayer._mainTexture;
  20939. if (renderTarget._shouldRender()) {
  20940. this._renderId++;
  20941. renderTarget.render(false, false);
  20942. needsRestoreFrameBuffer = true;
  20943. }
  20944. }
  20945. }
  20946. this._intermediateRendering = false;
  20947. this._renderId++;
  20948. }
  20949. if (needsRestoreFrameBuffer) {
  20950. engine.restoreDefaultFramebuffer(); // Restore back buffer
  20951. }
  20952. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  20953. // Prepare Frame
  20954. this.postProcessManager._prepareFrame();
  20955. // Backgrounds
  20956. var layerIndex;
  20957. var layer;
  20958. if (this.layers.length) {
  20959. engine.setDepthBuffer(false);
  20960. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  20961. layer = this.layers[layerIndex];
  20962. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  20963. layer.render();
  20964. }
  20965. }
  20966. engine.setDepthBuffer(true);
  20967. }
  20968. // Activate HighlightLayer stencil
  20969. if (renderhighlights) {
  20970. this._engine.setStencilBuffer(true);
  20971. }
  20972. // Render
  20973. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  20974. this._renderingManager.render(null, null, true, true);
  20975. this.onAfterDrawPhaseObservable.notifyObservers(this);
  20976. // Restore HighlightLayer stencil
  20977. if (renderhighlights) {
  20978. this._engine.setStencilBuffer(stencilState);
  20979. }
  20980. // Bounding boxes
  20981. if (this._boundingBoxRenderer) {
  20982. this._boundingBoxRenderer.render();
  20983. }
  20984. // Lens flares
  20985. if (this.lensFlaresEnabled) {
  20986. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  20987. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  20988. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  20989. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  20990. lensFlareSystem.render();
  20991. }
  20992. }
  20993. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  20994. }
  20995. // Foregrounds
  20996. if (this.layers.length) {
  20997. engine.setDepthBuffer(false);
  20998. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  20999. layer = this.layers[layerIndex];
  21000. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  21001. layer.render();
  21002. }
  21003. }
  21004. engine.setDepthBuffer(true);
  21005. }
  21006. // Highlight Layer
  21007. if (renderhighlights) {
  21008. engine.setDepthBuffer(false);
  21009. for (var i = 0; i < this.highlightLayers.length; i++) {
  21010. if (this.highlightLayers[i].shouldRender()) {
  21011. this.highlightLayers[i].render();
  21012. }
  21013. }
  21014. engine.setDepthBuffer(true);
  21015. }
  21016. // Finalize frame
  21017. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  21018. // Reset some special arrays
  21019. this._renderTargets.reset();
  21020. this._alternateRendering = false;
  21021. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  21022. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  21023. };
  21024. Scene.prototype._processSubCameras = function (camera) {
  21025. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  21026. this._renderForCamera(camera);
  21027. return;
  21028. }
  21029. // Update camera
  21030. if (this.activeCamera) {
  21031. this.activeCamera.update();
  21032. }
  21033. // rig cameras
  21034. for (var index = 0; index < camera._rigCameras.length; index++) {
  21035. this._renderForCamera(camera._rigCameras[index]);
  21036. }
  21037. this.activeCamera = camera;
  21038. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  21039. };
  21040. Scene.prototype._checkIntersections = function () {
  21041. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  21042. var sourceMesh = this._meshesForIntersections.data[index];
  21043. if (!sourceMesh.actionManager) {
  21044. continue;
  21045. }
  21046. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  21047. var action = sourceMesh.actionManager.actions[actionIndex];
  21048. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  21049. var parameters = action.getTriggerParameter();
  21050. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  21051. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  21052. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  21053. if (areIntersecting && currentIntersectionInProgress === -1) {
  21054. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  21055. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  21056. sourceMesh._intersectionsInProgress.push(otherMesh);
  21057. }
  21058. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  21059. sourceMesh._intersectionsInProgress.push(otherMesh);
  21060. }
  21061. }
  21062. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  21063. //They intersected, and now they don't.
  21064. //is this trigger an exit trigger? execute an event.
  21065. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  21066. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  21067. }
  21068. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  21069. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  21070. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  21071. }
  21072. }
  21073. }
  21074. }
  21075. }
  21076. };
  21077. Scene.prototype.render = function () {
  21078. if (this.isDisposed) {
  21079. return;
  21080. }
  21081. this._activeParticles.fetchNewFrame();
  21082. this._totalVertices.fetchNewFrame();
  21083. this._activeIndices.fetchNewFrame();
  21084. this._activeBones.fetchNewFrame();
  21085. this._meshesForIntersections.reset();
  21086. this.resetCachedMaterial();
  21087. this.onBeforeAnimationsObservable.notifyObservers(this);
  21088. // Actions
  21089. if (this.actionManager) {
  21090. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  21091. }
  21092. //Simplification Queue
  21093. if (this.simplificationQueue && !this.simplificationQueue.running) {
  21094. this.simplificationQueue.executeNext();
  21095. }
  21096. if (this._engine.isDeterministicLockStep()) {
  21097. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  21098. var defaultFPS = (60.0 / 1000.0);
  21099. var defaultFrameTime = 1000 / 60; // frame time in MS
  21100. if (this._physicsEngine) {
  21101. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  21102. }
  21103. var stepsTaken = 0;
  21104. var maxSubSteps = this._engine.getLockstepMaxSteps();
  21105. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  21106. internalSteps = Math.min(internalSteps, maxSubSteps);
  21107. do {
  21108. this.onBeforeStepObservable.notifyObservers(this);
  21109. // Animations
  21110. this._animationRatio = defaultFrameTime * defaultFPS;
  21111. this._animate();
  21112. this.onAfterAnimationsObservable.notifyObservers(this);
  21113. // Physics
  21114. if (this._physicsEngine) {
  21115. this.onBeforePhysicsObservable.notifyObservers(this);
  21116. this._physicsEngine._step(defaultFrameTime / 1000);
  21117. this.onAfterPhysicsObservable.notifyObservers(this);
  21118. }
  21119. this.onAfterStepObservable.notifyObservers(this);
  21120. this._currentStepId++;
  21121. stepsTaken++;
  21122. deltaTime -= defaultFrameTime;
  21123. } while (deltaTime > 0 && stepsTaken < internalSteps);
  21124. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  21125. }
  21126. else {
  21127. // Animations
  21128. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  21129. this._animationRatio = deltaTime * (60.0 / 1000.0);
  21130. this._animate();
  21131. this.onAfterAnimationsObservable.notifyObservers(this);
  21132. // Physics
  21133. if (this._physicsEngine) {
  21134. this.onBeforePhysicsObservable.notifyObservers(this);
  21135. this._physicsEngine._step(deltaTime / 1000.0);
  21136. this.onAfterPhysicsObservable.notifyObservers(this);
  21137. }
  21138. }
  21139. // update gamepad manager
  21140. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  21141. this._gamepadManager._checkGamepadsStatus();
  21142. }
  21143. // Before render
  21144. this.onBeforeRenderObservable.notifyObservers(this);
  21145. // Customs render targets
  21146. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  21147. var engine = this.getEngine();
  21148. var currentActiveCamera = this.activeCamera;
  21149. if (this.renderTargetsEnabled) {
  21150. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  21151. this._intermediateRendering = true;
  21152. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  21153. var renderTarget = this.customRenderTargets[customIndex];
  21154. if (renderTarget._shouldRender()) {
  21155. this._renderId++;
  21156. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  21157. if (!this.activeCamera)
  21158. throw new Error("Active camera not set");
  21159. // Viewport
  21160. engine.setViewport(this.activeCamera.viewport);
  21161. // Camera
  21162. this.updateTransformMatrix();
  21163. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  21164. }
  21165. }
  21166. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  21167. this._intermediateRendering = false;
  21168. this._renderId++;
  21169. }
  21170. // Restore back buffer
  21171. if (this.customRenderTargets.length > 0) {
  21172. engine.restoreDefaultFramebuffer();
  21173. }
  21174. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  21175. this.activeCamera = currentActiveCamera;
  21176. // Procedural textures
  21177. if (this.proceduralTexturesEnabled) {
  21178. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  21179. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  21180. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  21181. if (proceduralTexture._shouldRender()) {
  21182. proceduralTexture.render();
  21183. }
  21184. }
  21185. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  21186. }
  21187. // Clear
  21188. if (this.autoClearDepthAndStencil || this.autoClear) {
  21189. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  21190. }
  21191. // Shadows
  21192. if (this.shadowsEnabled) {
  21193. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  21194. var light = this.lights[lightIndex];
  21195. var shadowGenerator = light.getShadowGenerator();
  21196. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  21197. var shadowMap = (shadowGenerator.getShadowMap());
  21198. if (this.textures.indexOf(shadowMap) !== -1) {
  21199. this._renderTargets.push(shadowMap);
  21200. }
  21201. }
  21202. }
  21203. }
  21204. // Depth renderer
  21205. if (this._depthRenderer) {
  21206. this._renderTargets.push(this._depthRenderer.getDepthMap());
  21207. }
  21208. // Geometry renderer
  21209. if (this._geometryBufferRenderer) {
  21210. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  21211. }
  21212. // RenderPipeline
  21213. if (this._postProcessRenderPipelineManager) {
  21214. this._postProcessRenderPipelineManager.update();
  21215. }
  21216. // Multi-cameras?
  21217. if (this.activeCameras.length > 0) {
  21218. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  21219. if (cameraIndex > 0) {
  21220. this._engine.clear(null, false, true, true);
  21221. }
  21222. this._processSubCameras(this.activeCameras[cameraIndex]);
  21223. }
  21224. }
  21225. else {
  21226. if (!this.activeCamera) {
  21227. throw new Error("No camera defined");
  21228. }
  21229. this._processSubCameras(this.activeCamera);
  21230. }
  21231. // Intersection checks
  21232. this._checkIntersections();
  21233. // Update the audio listener attached to the camera
  21234. if (BABYLON.AudioEngine) {
  21235. this._updateAudioParameters();
  21236. }
  21237. // After render
  21238. if (this.afterRender) {
  21239. this.afterRender();
  21240. }
  21241. this.onAfterRenderObservable.notifyObservers(this);
  21242. // Cleaning
  21243. for (var index = 0; index < this._toBeDisposed.length; index++) {
  21244. var data = this._toBeDisposed.data[index];
  21245. if (data) {
  21246. data.dispose();
  21247. }
  21248. this._toBeDisposed[index] = null;
  21249. }
  21250. this._toBeDisposed.reset();
  21251. if (this.dumpNextRenderTargets) {
  21252. this.dumpNextRenderTargets = false;
  21253. }
  21254. this._activeBones.addCount(0, true);
  21255. this._activeIndices.addCount(0, true);
  21256. this._activeParticles.addCount(0, true);
  21257. };
  21258. Scene.prototype._updateAudioParameters = function () {
  21259. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  21260. return;
  21261. }
  21262. var listeningCamera;
  21263. var audioEngine = BABYLON.Engine.audioEngine;
  21264. if (this.activeCameras.length > 0) {
  21265. listeningCamera = this.activeCameras[0];
  21266. }
  21267. else {
  21268. listeningCamera = this.activeCamera;
  21269. }
  21270. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  21271. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  21272. // for VR cameras
  21273. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  21274. listeningCamera = listeningCamera.rigCameras[0];
  21275. }
  21276. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  21277. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  21278. cameraDirection.normalize();
  21279. // To avoid some errors on GearVR
  21280. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  21281. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  21282. }
  21283. var i;
  21284. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  21285. var sound = this.mainSoundTrack.soundCollection[i];
  21286. if (sound.useCustomAttenuation) {
  21287. sound.updateDistanceFromListener();
  21288. }
  21289. }
  21290. for (i = 0; i < this.soundTracks.length; i++) {
  21291. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  21292. sound = this.soundTracks[i].soundCollection[j];
  21293. if (sound.useCustomAttenuation) {
  21294. sound.updateDistanceFromListener();
  21295. }
  21296. }
  21297. }
  21298. }
  21299. };
  21300. Object.defineProperty(Scene.prototype, "audioEnabled", {
  21301. // Audio
  21302. get: function () {
  21303. return this._audioEnabled;
  21304. },
  21305. set: function (value) {
  21306. this._audioEnabled = value;
  21307. if (BABYLON.AudioEngine) {
  21308. if (this._audioEnabled) {
  21309. this._enableAudio();
  21310. }
  21311. else {
  21312. this._disableAudio();
  21313. }
  21314. }
  21315. },
  21316. enumerable: true,
  21317. configurable: true
  21318. });
  21319. Scene.prototype._disableAudio = function () {
  21320. var i;
  21321. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  21322. this.mainSoundTrack.soundCollection[i].pause();
  21323. }
  21324. for (i = 0; i < this.soundTracks.length; i++) {
  21325. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  21326. this.soundTracks[i].soundCollection[j].pause();
  21327. }
  21328. }
  21329. };
  21330. Scene.prototype._enableAudio = function () {
  21331. var i;
  21332. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  21333. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  21334. this.mainSoundTrack.soundCollection[i].play();
  21335. }
  21336. }
  21337. for (i = 0; i < this.soundTracks.length; i++) {
  21338. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  21339. if (this.soundTracks[i].soundCollection[j].isPaused) {
  21340. this.soundTracks[i].soundCollection[j].play();
  21341. }
  21342. }
  21343. }
  21344. };
  21345. Object.defineProperty(Scene.prototype, "headphone", {
  21346. get: function () {
  21347. return this._headphone;
  21348. },
  21349. set: function (value) {
  21350. this._headphone = value;
  21351. if (BABYLON.AudioEngine) {
  21352. if (this._headphone) {
  21353. this._switchAudioModeForHeadphones();
  21354. }
  21355. else {
  21356. this._switchAudioModeForNormalSpeakers();
  21357. }
  21358. }
  21359. },
  21360. enumerable: true,
  21361. configurable: true
  21362. });
  21363. Scene.prototype._switchAudioModeForHeadphones = function () {
  21364. this.mainSoundTrack.switchPanningModelToHRTF();
  21365. for (var i = 0; i < this.soundTracks.length; i++) {
  21366. this.soundTracks[i].switchPanningModelToHRTF();
  21367. }
  21368. };
  21369. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  21370. this.mainSoundTrack.switchPanningModelToEqualPower();
  21371. for (var i = 0; i < this.soundTracks.length; i++) {
  21372. this.soundTracks[i].switchPanningModelToEqualPower();
  21373. }
  21374. };
  21375. Scene.prototype.enableDepthRenderer = function () {
  21376. if (this._depthRenderer) {
  21377. return this._depthRenderer;
  21378. }
  21379. this._depthRenderer = new BABYLON.DepthRenderer(this);
  21380. return this._depthRenderer;
  21381. };
  21382. Scene.prototype.disableDepthRenderer = function () {
  21383. if (!this._depthRenderer) {
  21384. return;
  21385. }
  21386. this._depthRenderer.dispose();
  21387. this._depthRenderer = null;
  21388. };
  21389. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  21390. if (ratio === void 0) { ratio = 1; }
  21391. if (this._geometryBufferRenderer) {
  21392. return this._geometryBufferRenderer;
  21393. }
  21394. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  21395. if (!this._geometryBufferRenderer.isSupported) {
  21396. this._geometryBufferRenderer = null;
  21397. }
  21398. return this._geometryBufferRenderer;
  21399. };
  21400. Scene.prototype.disableGeometryBufferRenderer = function () {
  21401. if (!this._geometryBufferRenderer) {
  21402. return;
  21403. }
  21404. this._geometryBufferRenderer.dispose();
  21405. this._geometryBufferRenderer = null;
  21406. };
  21407. Scene.prototype.freezeMaterials = function () {
  21408. for (var i = 0; i < this.materials.length; i++) {
  21409. this.materials[i].freeze();
  21410. }
  21411. };
  21412. Scene.prototype.unfreezeMaterials = function () {
  21413. for (var i = 0; i < this.materials.length; i++) {
  21414. this.materials[i].unfreeze();
  21415. }
  21416. };
  21417. Scene.prototype.dispose = function () {
  21418. this.beforeRender = null;
  21419. this.afterRender = null;
  21420. this.skeletons = [];
  21421. this.morphTargetManagers = [];
  21422. this.importedMeshesFiles = new Array();
  21423. this.stopAllAnimations();
  21424. this.resetCachedMaterial();
  21425. if (this._depthRenderer) {
  21426. this._depthRenderer.dispose();
  21427. }
  21428. if (this._gamepadManager) {
  21429. this._gamepadManager.dispose();
  21430. this._gamepadManager = null;
  21431. }
  21432. // Smart arrays
  21433. if (this.activeCamera) {
  21434. this.activeCamera._activeMeshes.dispose();
  21435. this.activeCamera = null;
  21436. }
  21437. this._activeMeshes.dispose();
  21438. this._renderingManager.dispose();
  21439. this._processedMaterials.dispose();
  21440. this._activeParticleSystems.dispose();
  21441. this._activeSkeletons.dispose();
  21442. this._softwareSkinnedMeshes.dispose();
  21443. this._renderTargets.dispose();
  21444. if (this._boundingBoxRenderer) {
  21445. this._boundingBoxRenderer.dispose();
  21446. }
  21447. this._meshesForIntersections.dispose();
  21448. this._toBeDisposed.dispose();
  21449. // Abort active requests
  21450. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  21451. var request = _a[_i];
  21452. request.abort();
  21453. }
  21454. // Debug layer
  21455. if (this._debugLayer) {
  21456. this._debugLayer.hide();
  21457. }
  21458. // Events
  21459. this.onDisposeObservable.notifyObservers(this);
  21460. this.onDisposeObservable.clear();
  21461. this.onBeforeRenderObservable.clear();
  21462. this.onAfterRenderObservable.clear();
  21463. this.OnBeforeRenderTargetsRenderObservable.clear();
  21464. this.OnAfterRenderTargetsRenderObservable.clear();
  21465. this.onAfterStepObservable.clear();
  21466. this.onBeforeStepObservable.clear();
  21467. this.onBeforeActiveMeshesEvaluationObservable.clear();
  21468. this.onAfterActiveMeshesEvaluationObservable.clear();
  21469. this.onBeforeParticlesRenderingObservable.clear();
  21470. this.onAfterParticlesRenderingObservable.clear();
  21471. this.onBeforeSpritesRenderingObservable.clear();
  21472. this.onAfterSpritesRenderingObservable.clear();
  21473. this.onBeforeDrawPhaseObservable.clear();
  21474. this.onAfterDrawPhaseObservable.clear();
  21475. this.onBeforePhysicsObservable.clear();
  21476. this.onAfterPhysicsObservable.clear();
  21477. this.onBeforeAnimationsObservable.clear();
  21478. this.onAfterAnimationsObservable.clear();
  21479. this.onDataLoadedObservable.clear();
  21480. this.detachControl();
  21481. // Release sounds & sounds tracks
  21482. if (BABYLON.AudioEngine) {
  21483. this.disposeSounds();
  21484. }
  21485. // VR Helper
  21486. if (this.VRHelper) {
  21487. this.VRHelper.dispose();
  21488. }
  21489. // Detach cameras
  21490. var canvas = this._engine.getRenderingCanvas();
  21491. if (canvas) {
  21492. var index;
  21493. for (index = 0; index < this.cameras.length; index++) {
  21494. this.cameras[index].detachControl(canvas);
  21495. }
  21496. }
  21497. // Release animation groups
  21498. while (this.animationGroups.length) {
  21499. this.animationGroups[0].dispose();
  21500. }
  21501. // Release lights
  21502. while (this.lights.length) {
  21503. this.lights[0].dispose();
  21504. }
  21505. // Release meshes
  21506. while (this.meshes.length) {
  21507. this.meshes[0].dispose(true);
  21508. }
  21509. while (this.transformNodes.length) {
  21510. this.removeTransformNode(this.transformNodes[0]);
  21511. }
  21512. // Release cameras
  21513. while (this.cameras.length) {
  21514. this.cameras[0].dispose();
  21515. }
  21516. // Release materials
  21517. if (this.defaultMaterial) {
  21518. this.defaultMaterial.dispose();
  21519. }
  21520. while (this.multiMaterials.length) {
  21521. this.multiMaterials[0].dispose();
  21522. }
  21523. while (this.materials.length) {
  21524. this.materials[0].dispose();
  21525. }
  21526. // Release particles
  21527. while (this.particleSystems.length) {
  21528. this.particleSystems[0].dispose();
  21529. }
  21530. // Release sprites
  21531. while (this.spriteManagers.length) {
  21532. this.spriteManagers[0].dispose();
  21533. }
  21534. // Release postProcesses
  21535. while (this.postProcesses.length) {
  21536. this.postProcesses[0].dispose();
  21537. }
  21538. // Release layers
  21539. while (this.layers.length) {
  21540. this.layers[0].dispose();
  21541. }
  21542. while (this.highlightLayers.length) {
  21543. this.highlightLayers[0].dispose();
  21544. }
  21545. // Release textures
  21546. while (this.textures.length) {
  21547. this.textures[0].dispose();
  21548. }
  21549. // Release UBO
  21550. this._sceneUbo.dispose();
  21551. if (this._alternateSceneUbo) {
  21552. this._alternateSceneUbo.dispose();
  21553. }
  21554. // Post-processes
  21555. this.postProcessManager.dispose();
  21556. if (this._postProcessRenderPipelineManager) {
  21557. this._postProcessRenderPipelineManager.dispose();
  21558. }
  21559. // Physics
  21560. if (this._physicsEngine) {
  21561. this.disablePhysicsEngine();
  21562. }
  21563. // Remove from engine
  21564. index = this._engine.scenes.indexOf(this);
  21565. if (index > -1) {
  21566. this._engine.scenes.splice(index, 1);
  21567. }
  21568. this._engine.wipeCaches(true);
  21569. this._isDisposed = true;
  21570. };
  21571. Object.defineProperty(Scene.prototype, "isDisposed", {
  21572. get: function () {
  21573. return this._isDisposed;
  21574. },
  21575. enumerable: true,
  21576. configurable: true
  21577. });
  21578. // Release sounds & sounds tracks
  21579. Scene.prototype.disposeSounds = function () {
  21580. if (!this._mainSoundTrack) {
  21581. return;
  21582. }
  21583. this.mainSoundTrack.dispose();
  21584. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  21585. this.soundTracks[scIndex].dispose();
  21586. }
  21587. };
  21588. // Octrees
  21589. Scene.prototype.getWorldExtends = function () {
  21590. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  21591. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  21592. for (var index = 0; index < this.meshes.length; index++) {
  21593. var mesh = this.meshes[index];
  21594. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  21595. continue;
  21596. }
  21597. mesh.computeWorldMatrix(true);
  21598. var boundingInfo = mesh.getBoundingInfo();
  21599. var minBox = boundingInfo.boundingBox.minimumWorld;
  21600. var maxBox = boundingInfo.boundingBox.maximumWorld;
  21601. BABYLON.Tools.CheckExtends(minBox, min, max);
  21602. BABYLON.Tools.CheckExtends(maxBox, min, max);
  21603. }
  21604. return {
  21605. min: min,
  21606. max: max
  21607. };
  21608. };
  21609. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  21610. if (maxCapacity === void 0) { maxCapacity = 64; }
  21611. if (maxDepth === void 0) { maxDepth = 2; }
  21612. if (!this._selectionOctree) {
  21613. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  21614. }
  21615. var worldExtends = this.getWorldExtends();
  21616. // Update octree
  21617. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  21618. return this._selectionOctree;
  21619. };
  21620. // Picking
  21621. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  21622. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  21623. var result = BABYLON.Ray.Zero();
  21624. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  21625. return result;
  21626. };
  21627. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  21628. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  21629. var engine = this._engine;
  21630. if (!camera) {
  21631. if (!this.activeCamera)
  21632. throw new Error("Active camera not set");
  21633. camera = this.activeCamera;
  21634. }
  21635. var cameraViewport = camera.viewport;
  21636. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  21637. // Moving coordinates to local viewport world
  21638. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  21639. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  21640. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  21641. return this;
  21642. };
  21643. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  21644. var result = BABYLON.Ray.Zero();
  21645. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  21646. return result;
  21647. };
  21648. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  21649. if (!BABYLON.PickingInfo) {
  21650. return this;
  21651. }
  21652. var engine = this._engine;
  21653. if (!camera) {
  21654. if (!this.activeCamera)
  21655. throw new Error("Active camera not set");
  21656. camera = this.activeCamera;
  21657. }
  21658. var cameraViewport = camera.viewport;
  21659. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  21660. var identity = BABYLON.Matrix.Identity();
  21661. // Moving coordinates to local viewport world
  21662. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  21663. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  21664. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  21665. return this;
  21666. };
  21667. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  21668. if (!BABYLON.PickingInfo) {
  21669. return null;
  21670. }
  21671. var pickingInfo = null;
  21672. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  21673. var mesh = this.meshes[meshIndex];
  21674. if (predicate) {
  21675. if (!predicate(mesh)) {
  21676. continue;
  21677. }
  21678. }
  21679. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  21680. continue;
  21681. }
  21682. var world = mesh.getWorldMatrix();
  21683. var ray = rayFunction(world);
  21684. var result = mesh.intersects(ray, fastCheck);
  21685. if (!result || !result.hit)
  21686. continue;
  21687. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  21688. continue;
  21689. pickingInfo = result;
  21690. if (fastCheck) {
  21691. break;
  21692. }
  21693. }
  21694. return pickingInfo || new BABYLON.PickingInfo();
  21695. };
  21696. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  21697. if (!BABYLON.PickingInfo) {
  21698. return null;
  21699. }
  21700. var pickingInfos = new Array();
  21701. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  21702. var mesh = this.meshes[meshIndex];
  21703. if (predicate) {
  21704. if (!predicate(mesh)) {
  21705. continue;
  21706. }
  21707. }
  21708. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  21709. continue;
  21710. }
  21711. var world = mesh.getWorldMatrix();
  21712. var ray = rayFunction(world);
  21713. var result = mesh.intersects(ray, false);
  21714. if (!result || !result.hit)
  21715. continue;
  21716. pickingInfos.push(result);
  21717. }
  21718. return pickingInfos;
  21719. };
  21720. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  21721. if (!BABYLON.PickingInfo) {
  21722. return null;
  21723. }
  21724. var pickingInfo = null;
  21725. if (!camera) {
  21726. if (!this.activeCamera) {
  21727. return null;
  21728. }
  21729. camera = this.activeCamera;
  21730. }
  21731. if (this.spriteManagers.length > 0) {
  21732. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  21733. var spriteManager = this.spriteManagers[spriteIndex];
  21734. if (!spriteManager.isPickable) {
  21735. continue;
  21736. }
  21737. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  21738. if (!result || !result.hit)
  21739. continue;
  21740. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  21741. continue;
  21742. pickingInfo = result;
  21743. if (fastCheck) {
  21744. break;
  21745. }
  21746. }
  21747. }
  21748. return pickingInfo || new BABYLON.PickingInfo();
  21749. };
  21750. /** Launch a ray to try to pick a mesh in the scene
  21751. * @param x position on screen
  21752. * @param y position on screen
  21753. * @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
  21754. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  21755. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  21756. */
  21757. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  21758. var _this = this;
  21759. if (!BABYLON.PickingInfo) {
  21760. return null;
  21761. }
  21762. return this._internalPick(function (world) {
  21763. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  21764. return _this._tempPickingRay;
  21765. }, predicate, fastCheck);
  21766. };
  21767. /** Launch a ray to try to pick a sprite in the scene
  21768. * @param x position on screen
  21769. * @param y position on screen
  21770. * @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
  21771. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  21772. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  21773. */
  21774. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  21775. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  21776. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  21777. };
  21778. /** Use the given ray to pick a mesh in the scene
  21779. * @param ray The ray to use to pick meshes
  21780. * @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
  21781. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  21782. */
  21783. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  21784. var _this = this;
  21785. return this._internalPick(function (world) {
  21786. if (!_this._pickWithRayInverseMatrix) {
  21787. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  21788. }
  21789. world.invertToRef(_this._pickWithRayInverseMatrix);
  21790. if (!_this._cachedRayForTransform) {
  21791. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  21792. }
  21793. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  21794. return _this._cachedRayForTransform;
  21795. }, predicate, fastCheck);
  21796. };
  21797. /**
  21798. * Launch a ray to try to pick a mesh in the scene
  21799. * @param x X position on screen
  21800. * @param y Y position on screen
  21801. * @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
  21802. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  21803. */
  21804. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  21805. var _this = this;
  21806. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  21807. };
  21808. /**
  21809. * Launch a ray to try to pick a mesh in the scene
  21810. * @param ray Ray to use
  21811. * @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
  21812. */
  21813. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  21814. var _this = this;
  21815. return this._internalMultiPick(function (world) {
  21816. if (!_this._pickWithRayInverseMatrix) {
  21817. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  21818. }
  21819. world.invertToRef(_this._pickWithRayInverseMatrix);
  21820. if (!_this._cachedRayForTransform) {
  21821. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  21822. }
  21823. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  21824. return _this._cachedRayForTransform;
  21825. }, predicate);
  21826. };
  21827. Scene.prototype.setPointerOverMesh = function (mesh) {
  21828. if (this._pointerOverMesh === mesh) {
  21829. return;
  21830. }
  21831. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  21832. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  21833. }
  21834. this._pointerOverMesh = mesh;
  21835. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  21836. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  21837. }
  21838. };
  21839. Scene.prototype.getPointerOverMesh = function () {
  21840. return this._pointerOverMesh;
  21841. };
  21842. Scene.prototype.setPointerOverSprite = function (sprite) {
  21843. if (this._pointerOverSprite === sprite) {
  21844. return;
  21845. }
  21846. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  21847. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  21848. }
  21849. this._pointerOverSprite = sprite;
  21850. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  21851. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  21852. }
  21853. };
  21854. Scene.prototype.getPointerOverSprite = function () {
  21855. return this._pointerOverSprite;
  21856. };
  21857. // Physics
  21858. Scene.prototype.getPhysicsEngine = function () {
  21859. return this._physicsEngine;
  21860. };
  21861. /**
  21862. * Enables physics to the current scene
  21863. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  21864. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  21865. * @return {boolean} was the physics engine initialized
  21866. */
  21867. Scene.prototype.enablePhysics = function (gravity, plugin) {
  21868. if (gravity === void 0) { gravity = null; }
  21869. if (this._physicsEngine) {
  21870. return true;
  21871. }
  21872. try {
  21873. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  21874. return true;
  21875. }
  21876. catch (e) {
  21877. BABYLON.Tools.Error(e.message);
  21878. return false;
  21879. }
  21880. };
  21881. Scene.prototype.disablePhysicsEngine = function () {
  21882. if (!this._physicsEngine) {
  21883. return;
  21884. }
  21885. this._physicsEngine.dispose();
  21886. this._physicsEngine = null;
  21887. };
  21888. Scene.prototype.isPhysicsEnabled = function () {
  21889. return this._physicsEngine !== undefined;
  21890. };
  21891. Scene.prototype.deleteCompoundImpostor = function (compound) {
  21892. var mesh = compound.parts[0].mesh;
  21893. if (mesh.physicsImpostor) {
  21894. mesh.physicsImpostor.dispose();
  21895. mesh.physicsImpostor = null;
  21896. }
  21897. };
  21898. // Misc.
  21899. Scene.prototype._rebuildGeometries = function () {
  21900. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  21901. var geometry = _a[_i];
  21902. geometry._rebuild();
  21903. }
  21904. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  21905. var mesh = _c[_b];
  21906. mesh._rebuild();
  21907. }
  21908. if (this.postProcessManager) {
  21909. this.postProcessManager._rebuild();
  21910. }
  21911. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  21912. var layer = _e[_d];
  21913. layer._rebuild();
  21914. }
  21915. for (var _f = 0, _g = this.highlightLayers; _f < _g.length; _f++) {
  21916. var highlightLayer = _g[_f];
  21917. highlightLayer._rebuild();
  21918. }
  21919. if (this._boundingBoxRenderer) {
  21920. this._boundingBoxRenderer._rebuild();
  21921. }
  21922. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  21923. var system = _j[_h];
  21924. system.rebuild();
  21925. }
  21926. if (this._postProcessRenderPipelineManager) {
  21927. this._postProcessRenderPipelineManager._rebuild();
  21928. }
  21929. };
  21930. Scene.prototype._rebuildTextures = function () {
  21931. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  21932. var texture = _a[_i];
  21933. texture._rebuild();
  21934. }
  21935. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  21936. };
  21937. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  21938. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  21939. if (replace === void 0) { replace = false; }
  21940. if (attachCameraControls === void 0) { attachCameraControls = false; }
  21941. // Dispose existing camera or light in replace mode.
  21942. if (replace) {
  21943. if (this.activeCamera) {
  21944. this.activeCamera.dispose();
  21945. this.activeCamera = null;
  21946. }
  21947. if (this.lights) {
  21948. for (var i = 0; i < this.lights.length; i++) {
  21949. this.lights[i].dispose();
  21950. }
  21951. }
  21952. }
  21953. // Light
  21954. if (this.lights.length === 0) {
  21955. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  21956. }
  21957. // Camera
  21958. if (!this.activeCamera) {
  21959. var worldExtends = this.getWorldExtends();
  21960. var worldSize = worldExtends.max.subtract(worldExtends.min);
  21961. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  21962. var camera;
  21963. var radius = worldSize.length() * 1.5;
  21964. if (createArcRotateCamera) {
  21965. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  21966. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  21967. arcRotateCamera.wheelPrecision = 100 / radius;
  21968. camera = arcRotateCamera;
  21969. }
  21970. else {
  21971. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  21972. freeCamera.setTarget(worldCenter);
  21973. camera = freeCamera;
  21974. }
  21975. camera.minZ = radius * 0.01;
  21976. camera.maxZ = radius * 1000;
  21977. camera.speed = radius * 0.2;
  21978. this.activeCamera = camera;
  21979. var canvas = this.getEngine().getRenderingCanvas();
  21980. if (attachCameraControls && canvas) {
  21981. camera.attachControl(canvas);
  21982. }
  21983. }
  21984. };
  21985. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  21986. if (pbr === void 0) { pbr = false; }
  21987. if (scale === void 0) { scale = 1000; }
  21988. if (blur === void 0) { blur = 0; }
  21989. if (environmentTexture) {
  21990. this.environmentTexture = environmentTexture;
  21991. }
  21992. if (!this.environmentTexture) {
  21993. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  21994. return null;
  21995. }
  21996. // Skybox
  21997. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  21998. if (pbr) {
  21999. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  22000. hdrSkyboxMaterial.backFaceCulling = false;
  22001. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  22002. if (hdrSkyboxMaterial.reflectionTexture) {
  22003. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  22004. }
  22005. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  22006. hdrSkyboxMaterial.disableLighting = true;
  22007. hdrSkyboxMaterial.twoSidedLighting = true;
  22008. hdrSkybox.infiniteDistance = true;
  22009. hdrSkybox.material = hdrSkyboxMaterial;
  22010. }
  22011. else {
  22012. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  22013. skyboxMaterial.backFaceCulling = false;
  22014. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  22015. if (skyboxMaterial.reflectionTexture) {
  22016. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  22017. }
  22018. skyboxMaterial.disableLighting = true;
  22019. hdrSkybox.infiniteDistance = true;
  22020. hdrSkybox.material = skyboxMaterial;
  22021. }
  22022. return hdrSkybox;
  22023. };
  22024. Scene.prototype.createDefaultEnvironment = function (options) {
  22025. if (BABYLON.EnvironmentHelper) {
  22026. return new BABYLON.EnvironmentHelper(options, this);
  22027. }
  22028. return null;
  22029. };
  22030. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  22031. if (webVROptions === void 0) { webVROptions = {}; }
  22032. return new BABYLON.VRExperienceHelper(this, webVROptions);
  22033. };
  22034. // Tags
  22035. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  22036. if (tagsQuery === undefined) {
  22037. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  22038. return list;
  22039. }
  22040. var listByTags = [];
  22041. forEach = forEach || (function (item) { return; });
  22042. for (var i in list) {
  22043. var item = list[i];
  22044. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  22045. listByTags.push(item);
  22046. forEach(item);
  22047. }
  22048. }
  22049. return listByTags;
  22050. };
  22051. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  22052. return this._getByTags(this.meshes, tagsQuery, forEach);
  22053. };
  22054. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  22055. return this._getByTags(this.cameras, tagsQuery, forEach);
  22056. };
  22057. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  22058. return this._getByTags(this.lights, tagsQuery, forEach);
  22059. };
  22060. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  22061. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  22062. };
  22063. /**
  22064. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  22065. * This allowed control for front to back rendering or reversly depending of the special needs.
  22066. *
  22067. * @param renderingGroupId The rendering group id corresponding to its index
  22068. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  22069. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  22070. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  22071. */
  22072. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  22073. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  22074. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  22075. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  22076. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  22077. };
  22078. /**
  22079. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  22080. *
  22081. * @param renderingGroupId The rendering group id corresponding to its index
  22082. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  22083. * @param depth Automatically clears depth between groups if true and autoClear is true.
  22084. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  22085. */
  22086. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  22087. if (depth === void 0) { depth = true; }
  22088. if (stencil === void 0) { stencil = true; }
  22089. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  22090. };
  22091. /**
  22092. * Will flag all materials as dirty to trigger new shader compilation
  22093. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  22094. */
  22095. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  22096. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  22097. var material = _a[_i];
  22098. if (predicate && !predicate(material)) {
  22099. continue;
  22100. }
  22101. material.markAsDirty(flag);
  22102. }
  22103. };
  22104. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  22105. var _this = this;
  22106. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  22107. this._activeRequests.push(request);
  22108. request.onCompleteObservable.add(function (request) {
  22109. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  22110. });
  22111. return request;
  22112. };
  22113. // Statics
  22114. Scene._FOGMODE_NONE = 0;
  22115. Scene._FOGMODE_EXP = 1;
  22116. Scene._FOGMODE_EXP2 = 2;
  22117. Scene._FOGMODE_LINEAR = 3;
  22118. Scene._uniqueIdCounter = 0;
  22119. Scene.MinDeltaTime = 1.0;
  22120. Scene.MaxDeltaTime = 1000.0;
  22121. /** The distance in pixel that you have to move to prevent some events */
  22122. Scene.DragMovementThreshold = 10; // in pixels
  22123. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  22124. Scene.LongPressDelay = 500; // in milliseconds
  22125. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  22126. Scene.DoubleClickDelay = 300; // in milliseconds
  22127. /** If you need to check double click without raising a single click at first click, enable this flag */
  22128. Scene.ExclusiveDoubleClickMode = false;
  22129. return Scene;
  22130. }());
  22131. BABYLON.Scene = Scene;
  22132. })(BABYLON || (BABYLON = {}));
  22133. //# sourceMappingURL=babylon.scene.js.map
  22134. var BABYLON;
  22135. (function (BABYLON) {
  22136. var Buffer = /** @class */ (function () {
  22137. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  22138. if (instanced === void 0) { instanced = false; }
  22139. if (engine instanceof BABYLON.Mesh) {
  22140. this._engine = engine.getScene().getEngine();
  22141. }
  22142. else {
  22143. this._engine = engine;
  22144. }
  22145. this._updatable = updatable;
  22146. this._data = data;
  22147. this._strideSize = stride;
  22148. if (!postponeInternalCreation) {
  22149. this.create();
  22150. }
  22151. this._instanced = instanced;
  22152. this._instanceDivisor = instanced ? 1 : 0;
  22153. }
  22154. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  22155. // a lot of these parameters are ignored as they are overriden by the buffer
  22156. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  22157. };
  22158. // Properties
  22159. Buffer.prototype.isUpdatable = function () {
  22160. return this._updatable;
  22161. };
  22162. Buffer.prototype.getData = function () {
  22163. return this._data;
  22164. };
  22165. Buffer.prototype.getBuffer = function () {
  22166. return this._buffer;
  22167. };
  22168. Buffer.prototype.getStrideSize = function () {
  22169. return this._strideSize;
  22170. };
  22171. Buffer.prototype.getIsInstanced = function () {
  22172. return this._instanced;
  22173. };
  22174. Object.defineProperty(Buffer.prototype, "instanceDivisor", {
  22175. get: function () {
  22176. return this._instanceDivisor;
  22177. },
  22178. set: function (value) {
  22179. this._instanceDivisor = value;
  22180. if (value == 0) {
  22181. this._instanced = false;
  22182. }
  22183. else {
  22184. this._instanced = true;
  22185. }
  22186. },
  22187. enumerable: true,
  22188. configurable: true
  22189. });
  22190. // Methods
  22191. Buffer.prototype.create = function (data) {
  22192. if (data === void 0) { data = null; }
  22193. if (!data && this._buffer) {
  22194. return; // nothing to do
  22195. }
  22196. data = data || this._data;
  22197. if (!data) {
  22198. return;
  22199. }
  22200. if (!this._buffer) {
  22201. if (this._updatable) {
  22202. this._buffer = this._engine.createDynamicVertexBuffer(data);
  22203. this._data = data;
  22204. }
  22205. else {
  22206. this._buffer = this._engine.createVertexBuffer(data);
  22207. }
  22208. }
  22209. else if (this._updatable) {
  22210. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  22211. this._data = data;
  22212. }
  22213. };
  22214. Buffer.prototype._rebuild = function () {
  22215. this._buffer = null;
  22216. this.create(this._data);
  22217. };
  22218. Buffer.prototype.update = function (data) {
  22219. this.create(data);
  22220. };
  22221. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  22222. if (!this._buffer) {
  22223. return;
  22224. }
  22225. if (this._updatable) {
  22226. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  22227. this._data = null;
  22228. }
  22229. };
  22230. Buffer.prototype.dispose = function () {
  22231. if (!this._buffer) {
  22232. return;
  22233. }
  22234. if (this._engine._releaseBuffer(this._buffer)) {
  22235. this._buffer = null;
  22236. }
  22237. };
  22238. return Buffer;
  22239. }());
  22240. BABYLON.Buffer = Buffer;
  22241. })(BABYLON || (BABYLON = {}));
  22242. //# sourceMappingURL=babylon.buffer.js.map
  22243. var BABYLON;
  22244. (function (BABYLON) {
  22245. var VertexBuffer = /** @class */ (function () {
  22246. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  22247. if (!stride) {
  22248. // Deduce stride from kind
  22249. switch (kind) {
  22250. case VertexBuffer.PositionKind:
  22251. stride = 3;
  22252. break;
  22253. case VertexBuffer.NormalKind:
  22254. stride = 3;
  22255. break;
  22256. case VertexBuffer.UVKind:
  22257. case VertexBuffer.UV2Kind:
  22258. case VertexBuffer.UV3Kind:
  22259. case VertexBuffer.UV4Kind:
  22260. case VertexBuffer.UV5Kind:
  22261. case VertexBuffer.UV6Kind:
  22262. stride = 2;
  22263. break;
  22264. case VertexBuffer.TangentKind:
  22265. case VertexBuffer.ColorKind:
  22266. stride = 4;
  22267. break;
  22268. case VertexBuffer.MatricesIndicesKind:
  22269. case VertexBuffer.MatricesIndicesExtraKind:
  22270. stride = 4;
  22271. break;
  22272. case VertexBuffer.MatricesWeightsKind:
  22273. case VertexBuffer.MatricesWeightsExtraKind:
  22274. default:
  22275. stride = 4;
  22276. break;
  22277. }
  22278. }
  22279. if (data instanceof BABYLON.Buffer) {
  22280. if (!stride) {
  22281. stride = data.getStrideSize();
  22282. }
  22283. this._buffer = data;
  22284. this._ownsBuffer = false;
  22285. }
  22286. else {
  22287. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  22288. this._ownsBuffer = true;
  22289. }
  22290. this._stride = stride;
  22291. this._offset = offset ? offset : 0;
  22292. this._size = size ? size : stride;
  22293. this._kind = kind;
  22294. }
  22295. VertexBuffer.prototype._rebuild = function () {
  22296. if (!this._buffer) {
  22297. return;
  22298. }
  22299. this._buffer._rebuild();
  22300. };
  22301. /**
  22302. * Returns the kind of the VertexBuffer (string).
  22303. */
  22304. VertexBuffer.prototype.getKind = function () {
  22305. return this._kind;
  22306. };
  22307. // Properties
  22308. /**
  22309. * Boolean : is the VertexBuffer updatable ?
  22310. */
  22311. VertexBuffer.prototype.isUpdatable = function () {
  22312. return this._buffer.isUpdatable();
  22313. };
  22314. /**
  22315. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  22316. */
  22317. VertexBuffer.prototype.getData = function () {
  22318. return this._buffer.getData();
  22319. };
  22320. /**
  22321. * Returns the WebGLBuffer associated to the VertexBuffer.
  22322. */
  22323. VertexBuffer.prototype.getBuffer = function () {
  22324. return this._buffer.getBuffer();
  22325. };
  22326. /**
  22327. * Returns the stride of the VertexBuffer (integer).
  22328. */
  22329. VertexBuffer.prototype.getStrideSize = function () {
  22330. return this._stride;
  22331. };
  22332. /**
  22333. * Returns the offset (integer).
  22334. */
  22335. VertexBuffer.prototype.getOffset = function () {
  22336. return this._offset;
  22337. };
  22338. /**
  22339. * Returns the VertexBuffer total size (integer).
  22340. */
  22341. VertexBuffer.prototype.getSize = function () {
  22342. return this._size;
  22343. };
  22344. /**
  22345. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  22346. */
  22347. VertexBuffer.prototype.getIsInstanced = function () {
  22348. return this._buffer.getIsInstanced();
  22349. };
  22350. /**
  22351. * Returns the instancing divisor, zero for non-instanced (integer).
  22352. */
  22353. VertexBuffer.prototype.getInstanceDivisor = function () {
  22354. return this._buffer.instanceDivisor;
  22355. };
  22356. // Methods
  22357. /**
  22358. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  22359. * Returns the created WebGLBuffer.
  22360. */
  22361. VertexBuffer.prototype.create = function (data) {
  22362. return this._buffer.create(data);
  22363. };
  22364. /**
  22365. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  22366. * Returns the updated WebGLBuffer.
  22367. */
  22368. VertexBuffer.prototype.update = function (data) {
  22369. return this._buffer.update(data);
  22370. };
  22371. /**
  22372. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  22373. * Returns the directly updated WebGLBuffer.
  22374. */
  22375. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  22376. return this._buffer.updateDirectly(data, offset);
  22377. };
  22378. /**
  22379. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  22380. */
  22381. VertexBuffer.prototype.dispose = function () {
  22382. if (this._ownsBuffer) {
  22383. this._buffer.dispose();
  22384. }
  22385. };
  22386. Object.defineProperty(VertexBuffer, "PositionKind", {
  22387. get: function () {
  22388. return VertexBuffer._PositionKind;
  22389. },
  22390. enumerable: true,
  22391. configurable: true
  22392. });
  22393. Object.defineProperty(VertexBuffer, "NormalKind", {
  22394. get: function () {
  22395. return VertexBuffer._NormalKind;
  22396. },
  22397. enumerable: true,
  22398. configurable: true
  22399. });
  22400. Object.defineProperty(VertexBuffer, "TangentKind", {
  22401. get: function () {
  22402. return VertexBuffer._TangentKind;
  22403. },
  22404. enumerable: true,
  22405. configurable: true
  22406. });
  22407. Object.defineProperty(VertexBuffer, "UVKind", {
  22408. get: function () {
  22409. return VertexBuffer._UVKind;
  22410. },
  22411. enumerable: true,
  22412. configurable: true
  22413. });
  22414. Object.defineProperty(VertexBuffer, "UV2Kind", {
  22415. get: function () {
  22416. return VertexBuffer._UV2Kind;
  22417. },
  22418. enumerable: true,
  22419. configurable: true
  22420. });
  22421. Object.defineProperty(VertexBuffer, "UV3Kind", {
  22422. get: function () {
  22423. return VertexBuffer._UV3Kind;
  22424. },
  22425. enumerable: true,
  22426. configurable: true
  22427. });
  22428. Object.defineProperty(VertexBuffer, "UV4Kind", {
  22429. get: function () {
  22430. return VertexBuffer._UV4Kind;
  22431. },
  22432. enumerable: true,
  22433. configurable: true
  22434. });
  22435. Object.defineProperty(VertexBuffer, "UV5Kind", {
  22436. get: function () {
  22437. return VertexBuffer._UV5Kind;
  22438. },
  22439. enumerable: true,
  22440. configurable: true
  22441. });
  22442. Object.defineProperty(VertexBuffer, "UV6Kind", {
  22443. get: function () {
  22444. return VertexBuffer._UV6Kind;
  22445. },
  22446. enumerable: true,
  22447. configurable: true
  22448. });
  22449. Object.defineProperty(VertexBuffer, "ColorKind", {
  22450. get: function () {
  22451. return VertexBuffer._ColorKind;
  22452. },
  22453. enumerable: true,
  22454. configurable: true
  22455. });
  22456. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  22457. get: function () {
  22458. return VertexBuffer._MatricesIndicesKind;
  22459. },
  22460. enumerable: true,
  22461. configurable: true
  22462. });
  22463. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  22464. get: function () {
  22465. return VertexBuffer._MatricesWeightsKind;
  22466. },
  22467. enumerable: true,
  22468. configurable: true
  22469. });
  22470. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  22471. get: function () {
  22472. return VertexBuffer._MatricesIndicesExtraKind;
  22473. },
  22474. enumerable: true,
  22475. configurable: true
  22476. });
  22477. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  22478. get: function () {
  22479. return VertexBuffer._MatricesWeightsExtraKind;
  22480. },
  22481. enumerable: true,
  22482. configurable: true
  22483. });
  22484. // Enums
  22485. VertexBuffer._PositionKind = "position";
  22486. VertexBuffer._NormalKind = "normal";
  22487. VertexBuffer._TangentKind = "tangent";
  22488. VertexBuffer._UVKind = "uv";
  22489. VertexBuffer._UV2Kind = "uv2";
  22490. VertexBuffer._UV3Kind = "uv3";
  22491. VertexBuffer._UV4Kind = "uv4";
  22492. VertexBuffer._UV5Kind = "uv5";
  22493. VertexBuffer._UV6Kind = "uv6";
  22494. VertexBuffer._ColorKind = "color";
  22495. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  22496. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  22497. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  22498. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  22499. return VertexBuffer;
  22500. }());
  22501. BABYLON.VertexBuffer = VertexBuffer;
  22502. })(BABYLON || (BABYLON = {}));
  22503. //# sourceMappingURL=babylon.vertexBuffer.js.map
  22504. var BABYLON;
  22505. (function (BABYLON) {
  22506. var InternalTexture = /** @class */ (function () {
  22507. function InternalTexture(engine, dataSource) {
  22508. this.onLoadedObservable = new BABYLON.Observable();
  22509. // Private
  22510. this._initialSlot = -1;
  22511. this._designatedSlot = -1;
  22512. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  22513. this._references = 1;
  22514. this._engine = engine;
  22515. this._dataSource = dataSource;
  22516. this._webGLTexture = engine._createTexture();
  22517. }
  22518. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  22519. get: function () {
  22520. return this._dataSource;
  22521. },
  22522. enumerable: true,
  22523. configurable: true
  22524. });
  22525. InternalTexture.prototype.incrementReferences = function () {
  22526. this._references++;
  22527. };
  22528. InternalTexture.prototype.updateSize = function (width, height, depth) {
  22529. if (depth === void 0) { depth = 1; }
  22530. this.width = width;
  22531. this.height = height;
  22532. this.depth = depth;
  22533. this.baseWidth = width;
  22534. this.baseHeight = height;
  22535. this.baseDepth = depth;
  22536. this._size = width * height * depth;
  22537. };
  22538. InternalTexture.prototype._rebuild = function () {
  22539. var _this = this;
  22540. var proxy;
  22541. this.isReady = false;
  22542. this._cachedCoordinatesMode = null;
  22543. this._cachedWrapU = null;
  22544. this._cachedWrapV = null;
  22545. this._cachedAnisotropicFilteringLevel = null;
  22546. switch (this._dataSource) {
  22547. case InternalTexture.DATASOURCE_TEMP:
  22548. return;
  22549. case InternalTexture.DATASOURCE_URL:
  22550. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  22551. _this.isReady = true;
  22552. }, null, this._buffer, undefined, this.format);
  22553. proxy._swapAndDie(this);
  22554. return;
  22555. case InternalTexture.DATASOURCE_RAW:
  22556. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  22557. proxy._swapAndDie(this);
  22558. this.isReady = true;
  22559. return;
  22560. case InternalTexture.DATASOURCE_RAW3D:
  22561. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  22562. proxy._swapAndDie(this);
  22563. this.isReady = true;
  22564. return;
  22565. case InternalTexture.DATASOURCE_DYNAMIC:
  22566. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  22567. proxy._swapAndDie(this);
  22568. // The engine will make sure to update content so no need to flag it as isReady = true
  22569. return;
  22570. case InternalTexture.DATASOURCE_RENDERTARGET:
  22571. var options = new BABYLON.RenderTargetCreationOptions();
  22572. options.generateDepthBuffer = this._generateDepthBuffer;
  22573. options.generateMipMaps = this.generateMipMaps;
  22574. options.generateStencilBuffer = this._generateStencilBuffer;
  22575. options.samplingMode = this.samplingMode;
  22576. options.type = this.type;
  22577. if (this.isCube) {
  22578. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  22579. }
  22580. else {
  22581. var size = {
  22582. width: this.width,
  22583. height: this.height
  22584. };
  22585. proxy = this._engine.createRenderTargetTexture(size, options);
  22586. }
  22587. proxy._swapAndDie(this);
  22588. this.isReady = true;
  22589. return;
  22590. case InternalTexture.DATASOURCE_CUBE:
  22591. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  22592. _this.isReady = true;
  22593. }, null, this.format, this._extension);
  22594. proxy._swapAndDie(this);
  22595. return;
  22596. case InternalTexture.DATASOURCE_CUBERAW:
  22597. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  22598. proxy._swapAndDie(this);
  22599. this.isReady = true;
  22600. return;
  22601. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  22602. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  22603. if (proxy) {
  22604. proxy._swapAndDie(_this);
  22605. }
  22606. _this.isReady = true;
  22607. }, null, this.format, this._extension);
  22608. return;
  22609. }
  22610. };
  22611. InternalTexture.prototype._swapAndDie = function (target) {
  22612. target._webGLTexture = this._webGLTexture;
  22613. if (this._framebuffer) {
  22614. target._framebuffer = this._framebuffer;
  22615. }
  22616. if (this._depthStencilBuffer) {
  22617. target._depthStencilBuffer = this._depthStencilBuffer;
  22618. }
  22619. if (this._lodTextureHigh) {
  22620. if (target._lodTextureHigh) {
  22621. target._lodTextureHigh.dispose();
  22622. }
  22623. target._lodTextureHigh = this._lodTextureHigh;
  22624. }
  22625. if (this._lodTextureMid) {
  22626. if (target._lodTextureMid) {
  22627. target._lodTextureMid.dispose();
  22628. }
  22629. target._lodTextureMid = this._lodTextureMid;
  22630. }
  22631. if (this._lodTextureLow) {
  22632. if (target._lodTextureLow) {
  22633. target._lodTextureLow.dispose();
  22634. }
  22635. target._lodTextureLow = this._lodTextureLow;
  22636. }
  22637. var cache = this._engine.getLoadedTexturesCache();
  22638. var index = cache.indexOf(this);
  22639. if (index !== -1) {
  22640. cache.splice(index, 1);
  22641. }
  22642. };
  22643. InternalTexture.prototype.dispose = function () {
  22644. if (!this._webGLTexture) {
  22645. return;
  22646. }
  22647. this._references--;
  22648. if (this._references === 0) {
  22649. this._engine._releaseTexture(this);
  22650. this._webGLTexture = null;
  22651. }
  22652. };
  22653. InternalTexture.DATASOURCE_UNKNOWN = 0;
  22654. InternalTexture.DATASOURCE_URL = 1;
  22655. InternalTexture.DATASOURCE_TEMP = 2;
  22656. InternalTexture.DATASOURCE_RAW = 3;
  22657. InternalTexture.DATASOURCE_DYNAMIC = 4;
  22658. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  22659. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  22660. InternalTexture.DATASOURCE_CUBE = 7;
  22661. InternalTexture.DATASOURCE_CUBERAW = 8;
  22662. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  22663. InternalTexture.DATASOURCE_RAW3D = 10;
  22664. return InternalTexture;
  22665. }());
  22666. BABYLON.InternalTexture = InternalTexture;
  22667. })(BABYLON || (BABYLON = {}));
  22668. //# sourceMappingURL=babylon.internalTexture.js.map
  22669. var BABYLON;
  22670. (function (BABYLON) {
  22671. var BaseTexture = /** @class */ (function () {
  22672. function BaseTexture(scene) {
  22673. this._hasAlpha = false;
  22674. this.getAlphaFromRGB = false;
  22675. this.level = 1;
  22676. this.coordinatesIndex = 0;
  22677. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  22678. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  22679. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  22680. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  22681. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  22682. this.isCube = false;
  22683. this.is3D = false;
  22684. this.gammaSpace = true;
  22685. this.invertZ = false;
  22686. this.lodLevelInAlpha = false;
  22687. this.lodGenerationOffset = 0.0;
  22688. this.lodGenerationScale = 0.8;
  22689. this.isRenderTarget = false;
  22690. this.animations = new Array();
  22691. /**
  22692. * An event triggered when the texture is disposed.
  22693. * @type {BABYLON.Observable}
  22694. */
  22695. this.onDisposeObservable = new BABYLON.Observable();
  22696. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  22697. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  22698. if (this._scene) {
  22699. this._scene.textures.push(this);
  22700. }
  22701. this._uid = null;
  22702. }
  22703. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  22704. get: function () {
  22705. return this._hasAlpha;
  22706. },
  22707. set: function (value) {
  22708. if (this._hasAlpha === value) {
  22709. return;
  22710. }
  22711. this._hasAlpha = value;
  22712. if (this._scene) {
  22713. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  22714. }
  22715. },
  22716. enumerable: true,
  22717. configurable: true
  22718. });
  22719. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  22720. get: function () {
  22721. return this._coordinatesMode;
  22722. },
  22723. set: function (value) {
  22724. if (this._coordinatesMode === value) {
  22725. return;
  22726. }
  22727. this._coordinatesMode = value;
  22728. if (this._scene) {
  22729. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  22730. }
  22731. },
  22732. enumerable: true,
  22733. configurable: true
  22734. });
  22735. Object.defineProperty(BaseTexture.prototype, "uid", {
  22736. get: function () {
  22737. if (!this._uid) {
  22738. this._uid = BABYLON.Tools.RandomId();
  22739. }
  22740. return this._uid;
  22741. },
  22742. enumerable: true,
  22743. configurable: true
  22744. });
  22745. BaseTexture.prototype.toString = function () {
  22746. return this.name;
  22747. };
  22748. BaseTexture.prototype.getClassName = function () {
  22749. return "BaseTexture";
  22750. };
  22751. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  22752. set: function (callback) {
  22753. if (this._onDisposeObserver) {
  22754. this.onDisposeObservable.remove(this._onDisposeObserver);
  22755. }
  22756. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  22757. },
  22758. enumerable: true,
  22759. configurable: true
  22760. });
  22761. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  22762. get: function () {
  22763. return true;
  22764. },
  22765. enumerable: true,
  22766. configurable: true
  22767. });
  22768. BaseTexture.prototype.getScene = function () {
  22769. return this._scene;
  22770. };
  22771. BaseTexture.prototype.getTextureMatrix = function () {
  22772. return BABYLON.Matrix.IdentityReadOnly;
  22773. };
  22774. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  22775. return BABYLON.Matrix.IdentityReadOnly;
  22776. };
  22777. BaseTexture.prototype.getInternalTexture = function () {
  22778. return this._texture;
  22779. };
  22780. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  22781. return !this.isBlocking || this.isReady();
  22782. };
  22783. BaseTexture.prototype.isReady = function () {
  22784. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  22785. this.delayLoad();
  22786. return false;
  22787. }
  22788. if (this._texture) {
  22789. return this._texture.isReady;
  22790. }
  22791. return false;
  22792. };
  22793. BaseTexture.prototype.getSize = function () {
  22794. if (this._texture && this._texture.width) {
  22795. return new BABYLON.Size(this._texture.width, this._texture.height);
  22796. }
  22797. if (this._texture && this._texture._size) {
  22798. return new BABYLON.Size(this._texture._size, this._texture._size);
  22799. }
  22800. return BABYLON.Size.Zero();
  22801. };
  22802. BaseTexture.prototype.getBaseSize = function () {
  22803. if (!this.isReady() || !this._texture)
  22804. return BABYLON.Size.Zero();
  22805. if (this._texture._size) {
  22806. return new BABYLON.Size(this._texture._size, this._texture._size);
  22807. }
  22808. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  22809. };
  22810. BaseTexture.prototype.scale = function (ratio) {
  22811. };
  22812. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  22813. get: function () {
  22814. return false;
  22815. },
  22816. enumerable: true,
  22817. configurable: true
  22818. });
  22819. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  22820. if (!this._scene) {
  22821. return null;
  22822. }
  22823. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  22824. for (var index = 0; index < texturesCache.length; index++) {
  22825. var texturesCacheEntry = texturesCache[index];
  22826. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  22827. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  22828. texturesCacheEntry.incrementReferences();
  22829. return texturesCacheEntry;
  22830. }
  22831. }
  22832. }
  22833. return null;
  22834. };
  22835. BaseTexture.prototype._rebuild = function () {
  22836. };
  22837. BaseTexture.prototype.delayLoad = function () {
  22838. };
  22839. BaseTexture.prototype.clone = function () {
  22840. return null;
  22841. };
  22842. Object.defineProperty(BaseTexture.prototype, "textureType", {
  22843. get: function () {
  22844. if (!this._texture) {
  22845. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  22846. }
  22847. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  22848. },
  22849. enumerable: true,
  22850. configurable: true
  22851. });
  22852. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  22853. get: function () {
  22854. if (!this._texture) {
  22855. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  22856. }
  22857. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  22858. },
  22859. enumerable: true,
  22860. configurable: true
  22861. });
  22862. BaseTexture.prototype.readPixels = function (faceIndex) {
  22863. if (faceIndex === void 0) { faceIndex = 0; }
  22864. if (!this._texture) {
  22865. return null;
  22866. }
  22867. var size = this.getSize();
  22868. var scene = this.getScene();
  22869. if (!scene) {
  22870. return null;
  22871. }
  22872. var engine = scene.getEngine();
  22873. if (this._texture.isCube) {
  22874. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  22875. }
  22876. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  22877. };
  22878. BaseTexture.prototype.releaseInternalTexture = function () {
  22879. if (this._texture) {
  22880. this._texture.dispose();
  22881. this._texture = null;
  22882. }
  22883. };
  22884. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  22885. get: function () {
  22886. if (!this._texture || !BABYLON.Internals.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  22887. return null;
  22888. }
  22889. if (!this._texture._sphericalPolynomial) {
  22890. this._texture._sphericalPolynomial =
  22891. BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  22892. }
  22893. return this._texture._sphericalPolynomial;
  22894. },
  22895. set: function (value) {
  22896. if (this._texture) {
  22897. this._texture._sphericalPolynomial = value;
  22898. }
  22899. },
  22900. enumerable: true,
  22901. configurable: true
  22902. });
  22903. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  22904. get: function () {
  22905. if (this._texture) {
  22906. return this._texture._lodTextureHigh;
  22907. }
  22908. return null;
  22909. },
  22910. enumerable: true,
  22911. configurable: true
  22912. });
  22913. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  22914. get: function () {
  22915. if (this._texture) {
  22916. return this._texture._lodTextureMid;
  22917. }
  22918. return null;
  22919. },
  22920. enumerable: true,
  22921. configurable: true
  22922. });
  22923. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  22924. get: function () {
  22925. if (this._texture) {
  22926. return this._texture._lodTextureLow;
  22927. }
  22928. return null;
  22929. },
  22930. enumerable: true,
  22931. configurable: true
  22932. });
  22933. BaseTexture.prototype.dispose = function () {
  22934. if (!this._scene) {
  22935. return;
  22936. }
  22937. // Animations
  22938. this._scene.stopAnimation(this);
  22939. // Remove from scene
  22940. this._scene._removePendingData(this);
  22941. var index = this._scene.textures.indexOf(this);
  22942. if (index >= 0) {
  22943. this._scene.textures.splice(index, 1);
  22944. }
  22945. if (this._texture === undefined) {
  22946. return;
  22947. }
  22948. // Release
  22949. this.releaseInternalTexture();
  22950. // Callback
  22951. this.onDisposeObservable.notifyObservers(this);
  22952. this.onDisposeObservable.clear();
  22953. };
  22954. BaseTexture.prototype.serialize = function () {
  22955. if (!this.name) {
  22956. return null;
  22957. }
  22958. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22959. // Animations
  22960. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22961. return serializationObject;
  22962. };
  22963. BaseTexture.WhenAllReady = function (textures, callback) {
  22964. var numRemaining = textures.length;
  22965. if (numRemaining === 0) {
  22966. callback();
  22967. return;
  22968. }
  22969. var _loop_1 = function () {
  22970. texture = textures[i];
  22971. if (texture.isReady()) {
  22972. if (--numRemaining === 0) {
  22973. callback();
  22974. }
  22975. }
  22976. else {
  22977. onLoadObservable = texture.onLoadObservable;
  22978. var onLoadCallback_1 = function () {
  22979. onLoadObservable.removeCallback(onLoadCallback_1);
  22980. if (--numRemaining === 0) {
  22981. callback();
  22982. }
  22983. };
  22984. onLoadObservable.add(onLoadCallback_1);
  22985. }
  22986. };
  22987. var texture, onLoadObservable;
  22988. for (var i = 0; i < textures.length; i++) {
  22989. _loop_1();
  22990. }
  22991. };
  22992. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  22993. __decorate([
  22994. BABYLON.serialize()
  22995. ], BaseTexture.prototype, "name", void 0);
  22996. __decorate([
  22997. BABYLON.serialize("hasAlpha")
  22998. ], BaseTexture.prototype, "_hasAlpha", void 0);
  22999. __decorate([
  23000. BABYLON.serialize()
  23001. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  23002. __decorate([
  23003. BABYLON.serialize()
  23004. ], BaseTexture.prototype, "level", void 0);
  23005. __decorate([
  23006. BABYLON.serialize()
  23007. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  23008. __decorate([
  23009. BABYLON.serialize("coordinatesMode")
  23010. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  23011. __decorate([
  23012. BABYLON.serialize()
  23013. ], BaseTexture.prototype, "wrapU", void 0);
  23014. __decorate([
  23015. BABYLON.serialize()
  23016. ], BaseTexture.prototype, "wrapV", void 0);
  23017. __decorate([
  23018. BABYLON.serialize()
  23019. ], BaseTexture.prototype, "wrapR", void 0);
  23020. __decorate([
  23021. BABYLON.serialize()
  23022. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  23023. __decorate([
  23024. BABYLON.serialize()
  23025. ], BaseTexture.prototype, "isCube", void 0);
  23026. __decorate([
  23027. BABYLON.serialize()
  23028. ], BaseTexture.prototype, "is3D", void 0);
  23029. __decorate([
  23030. BABYLON.serialize()
  23031. ], BaseTexture.prototype, "gammaSpace", void 0);
  23032. __decorate([
  23033. BABYLON.serialize()
  23034. ], BaseTexture.prototype, "invertZ", void 0);
  23035. __decorate([
  23036. BABYLON.serialize()
  23037. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  23038. __decorate([
  23039. BABYLON.serialize()
  23040. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  23041. __decorate([
  23042. BABYLON.serialize()
  23043. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  23044. __decorate([
  23045. BABYLON.serialize()
  23046. ], BaseTexture.prototype, "isRenderTarget", void 0);
  23047. return BaseTexture;
  23048. }());
  23049. BABYLON.BaseTexture = BaseTexture;
  23050. })(BABYLON || (BABYLON = {}));
  23051. //# sourceMappingURL=babylon.baseTexture.js.map
  23052. var BABYLON;
  23053. (function (BABYLON) {
  23054. var Texture = /** @class */ (function (_super) {
  23055. __extends(Texture, _super);
  23056. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  23057. if (noMipmap === void 0) { noMipmap = false; }
  23058. if (invertY === void 0) { invertY = true; }
  23059. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  23060. if (onLoad === void 0) { onLoad = null; }
  23061. if (onError === void 0) { onError = null; }
  23062. if (buffer === void 0) { buffer = null; }
  23063. if (deleteBuffer === void 0) { deleteBuffer = false; }
  23064. var _this = _super.call(this, scene) || this;
  23065. _this.uOffset = 0;
  23066. _this.vOffset = 0;
  23067. _this.uScale = 1.0;
  23068. _this.vScale = 1.0;
  23069. _this.uAng = 0;
  23070. _this.vAng = 0;
  23071. _this.wAng = 0;
  23072. _this._isBlocking = true;
  23073. _this.name = url || "";
  23074. _this.url = url;
  23075. _this._noMipmap = noMipmap;
  23076. _this._invertY = invertY;
  23077. _this._samplingMode = samplingMode;
  23078. _this._buffer = buffer;
  23079. _this._deleteBuffer = deleteBuffer;
  23080. if (format) {
  23081. _this._format = format;
  23082. }
  23083. scene = _this.getScene();
  23084. if (!scene) {
  23085. return _this;
  23086. }
  23087. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  23088. var load = function () {
  23089. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  23090. _this.onLoadObservable.notifyObservers(_this);
  23091. }
  23092. if (onLoad) {
  23093. onLoad();
  23094. }
  23095. if (!_this.isBlocking && scene) {
  23096. scene.resetCachedMaterial();
  23097. }
  23098. };
  23099. if (!_this.url) {
  23100. _this._delayedOnLoad = load;
  23101. _this._delayedOnError = onError;
  23102. return _this;
  23103. }
  23104. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  23105. if (!_this._texture) {
  23106. if (!scene.useDelayedTextureLoading) {
  23107. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  23108. if (deleteBuffer) {
  23109. delete _this._buffer;
  23110. }
  23111. }
  23112. else {
  23113. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  23114. _this._delayedOnLoad = load;
  23115. _this._delayedOnError = onError;
  23116. }
  23117. }
  23118. else {
  23119. if (_this._texture.isReady) {
  23120. BABYLON.Tools.SetImmediate(function () { return load(); });
  23121. }
  23122. else {
  23123. _this._texture.onLoadedObservable.add(load);
  23124. }
  23125. }
  23126. return _this;
  23127. }
  23128. Object.defineProperty(Texture.prototype, "noMipmap", {
  23129. get: function () {
  23130. return this._noMipmap;
  23131. },
  23132. enumerable: true,
  23133. configurable: true
  23134. });
  23135. Object.defineProperty(Texture.prototype, "isBlocking", {
  23136. get: function () {
  23137. return this._isBlocking;
  23138. },
  23139. set: function (value) {
  23140. this._isBlocking = value;
  23141. },
  23142. enumerable: true,
  23143. configurable: true
  23144. });
  23145. Object.defineProperty(Texture.prototype, "samplingMode", {
  23146. get: function () {
  23147. return this._samplingMode;
  23148. },
  23149. enumerable: true,
  23150. configurable: true
  23151. });
  23152. Texture.prototype.updateURL = function (url) {
  23153. this.url = url;
  23154. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  23155. this.delayLoad();
  23156. };
  23157. Texture.prototype.delayLoad = function () {
  23158. var _this = this;
  23159. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  23160. return;
  23161. }
  23162. var scene = this.getScene();
  23163. if (!scene) {
  23164. return;
  23165. }
  23166. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  23167. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  23168. if (!this._texture) {
  23169. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  23170. if (this._deleteBuffer) {
  23171. delete this._buffer;
  23172. }
  23173. }
  23174. else {
  23175. if (this._texture.isReady) {
  23176. BABYLON.Tools.SetImmediate(function () {
  23177. if (!_this._delayedOnLoad) {
  23178. return;
  23179. }
  23180. _this._delayedOnLoad();
  23181. });
  23182. }
  23183. else {
  23184. if (this._delayedOnLoad) {
  23185. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  23186. }
  23187. }
  23188. }
  23189. };
  23190. Texture.prototype.updateSamplingMode = function (samplingMode) {
  23191. if (!this._texture) {
  23192. return;
  23193. }
  23194. var scene = this.getScene();
  23195. if (!scene) {
  23196. return;
  23197. }
  23198. this._samplingMode = samplingMode;
  23199. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  23200. };
  23201. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  23202. x *= this.uScale;
  23203. y *= this.vScale;
  23204. x -= 0.5 * this.uScale;
  23205. y -= 0.5 * this.vScale;
  23206. z -= 0.5;
  23207. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  23208. t.x += 0.5 * this.uScale + this.uOffset;
  23209. t.y += 0.5 * this.vScale + this.vOffset;
  23210. t.z += 0.5;
  23211. };
  23212. Texture.prototype.getTextureMatrix = function () {
  23213. var _this = this;
  23214. if (this.uOffset === this._cachedUOffset &&
  23215. this.vOffset === this._cachedVOffset &&
  23216. this.uScale === this._cachedUScale &&
  23217. this.vScale === this._cachedVScale &&
  23218. this.uAng === this._cachedUAng &&
  23219. this.vAng === this._cachedVAng &&
  23220. this.wAng === this._cachedWAng) {
  23221. return this._cachedTextureMatrix;
  23222. }
  23223. this._cachedUOffset = this.uOffset;
  23224. this._cachedVOffset = this.vOffset;
  23225. this._cachedUScale = this.uScale;
  23226. this._cachedVScale = this.vScale;
  23227. this._cachedUAng = this.uAng;
  23228. this._cachedVAng = this.vAng;
  23229. this._cachedWAng = this.wAng;
  23230. if (!this._cachedTextureMatrix) {
  23231. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  23232. this._rowGenerationMatrix = new BABYLON.Matrix();
  23233. this._t0 = BABYLON.Vector3.Zero();
  23234. this._t1 = BABYLON.Vector3.Zero();
  23235. this._t2 = BABYLON.Vector3.Zero();
  23236. }
  23237. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  23238. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  23239. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  23240. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  23241. this._t1.subtractInPlace(this._t0);
  23242. this._t2.subtractInPlace(this._t0);
  23243. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  23244. this._cachedTextureMatrix.m[0] = this._t1.x;
  23245. this._cachedTextureMatrix.m[1] = this._t1.y;
  23246. this._cachedTextureMatrix.m[2] = this._t1.z;
  23247. this._cachedTextureMatrix.m[4] = this._t2.x;
  23248. this._cachedTextureMatrix.m[5] = this._t2.y;
  23249. this._cachedTextureMatrix.m[6] = this._t2.z;
  23250. this._cachedTextureMatrix.m[8] = this._t0.x;
  23251. this._cachedTextureMatrix.m[9] = this._t0.y;
  23252. this._cachedTextureMatrix.m[10] = this._t0.z;
  23253. var scene = this.getScene();
  23254. if (!scene) {
  23255. return this._cachedTextureMatrix;
  23256. }
  23257. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  23258. return mat.hasTexture(_this);
  23259. });
  23260. return this._cachedTextureMatrix;
  23261. };
  23262. Texture.prototype.getReflectionTextureMatrix = function () {
  23263. var _this = this;
  23264. var scene = this.getScene();
  23265. if (!scene) {
  23266. return this._cachedTextureMatrix;
  23267. }
  23268. if (this.uOffset === this._cachedUOffset &&
  23269. this.vOffset === this._cachedVOffset &&
  23270. this.uScale === this._cachedUScale &&
  23271. this.vScale === this._cachedVScale &&
  23272. this.coordinatesMode === this._cachedCoordinatesMode) {
  23273. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  23274. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  23275. return this._cachedTextureMatrix;
  23276. }
  23277. }
  23278. else {
  23279. return this._cachedTextureMatrix;
  23280. }
  23281. }
  23282. if (!this._cachedTextureMatrix) {
  23283. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  23284. }
  23285. if (!this._projectionModeMatrix) {
  23286. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  23287. }
  23288. this._cachedUOffset = this.uOffset;
  23289. this._cachedVOffset = this.vOffset;
  23290. this._cachedUScale = this.uScale;
  23291. this._cachedVScale = this.vScale;
  23292. this._cachedCoordinatesMode = this.coordinatesMode;
  23293. switch (this.coordinatesMode) {
  23294. case Texture.PLANAR_MODE:
  23295. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  23296. this._cachedTextureMatrix[0] = this.uScale;
  23297. this._cachedTextureMatrix[5] = this.vScale;
  23298. this._cachedTextureMatrix[12] = this.uOffset;
  23299. this._cachedTextureMatrix[13] = this.vOffset;
  23300. break;
  23301. case Texture.PROJECTION_MODE:
  23302. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  23303. this._projectionModeMatrix.m[0] = 0.5;
  23304. this._projectionModeMatrix.m[5] = -0.5;
  23305. this._projectionModeMatrix.m[10] = 0.0;
  23306. this._projectionModeMatrix.m[12] = 0.5;
  23307. this._projectionModeMatrix.m[13] = 0.5;
  23308. this._projectionModeMatrix.m[14] = 1.0;
  23309. this._projectionModeMatrix.m[15] = 1.0;
  23310. var projectionMatrix = scene.getProjectionMatrix();
  23311. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  23312. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  23313. break;
  23314. default:
  23315. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  23316. break;
  23317. }
  23318. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  23319. return (mat.getActiveTextures().indexOf(_this) !== -1);
  23320. });
  23321. return this._cachedTextureMatrix;
  23322. };
  23323. Texture.prototype.clone = function () {
  23324. var _this = this;
  23325. return BABYLON.SerializationHelper.Clone(function () {
  23326. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  23327. }, this);
  23328. };
  23329. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  23330. get: function () {
  23331. if (!this._onLoadObservable) {
  23332. this._onLoadObservable = new BABYLON.Observable();
  23333. }
  23334. return this._onLoadObservable;
  23335. },
  23336. enumerable: true,
  23337. configurable: true
  23338. });
  23339. Texture.prototype.serialize = function () {
  23340. var serializationObject = _super.prototype.serialize.call(this);
  23341. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  23342. serializationObject.base64String = this._buffer;
  23343. serializationObject.name = serializationObject.name.replace("data:", "");
  23344. }
  23345. return serializationObject;
  23346. };
  23347. Texture.prototype.getClassName = function () {
  23348. return "Texture";
  23349. };
  23350. Texture.prototype.dispose = function () {
  23351. _super.prototype.dispose.call(this);
  23352. if (this.onLoadObservable) {
  23353. this.onLoadObservable.clear();
  23354. this._onLoadObservable = null;
  23355. }
  23356. this._delayedOnLoad = null;
  23357. this._delayedOnError = null;
  23358. };
  23359. // Statics
  23360. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  23361. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  23362. if (onLoad === void 0) { onLoad = null; }
  23363. if (onError === void 0) { onError = null; }
  23364. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  23365. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  23366. };
  23367. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  23368. if (parsedTexture.customType) {
  23369. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  23370. // Update Sampling Mode
  23371. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  23372. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  23373. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  23374. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  23375. }
  23376. }
  23377. return parsedCustomTexture;
  23378. }
  23379. if (parsedTexture.isCube) {
  23380. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  23381. }
  23382. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  23383. return null;
  23384. }
  23385. var texture = BABYLON.SerializationHelper.Parse(function () {
  23386. var generateMipMaps = true;
  23387. if (parsedTexture.noMipmap) {
  23388. generateMipMaps = false;
  23389. }
  23390. if (parsedTexture.mirrorPlane) {
  23391. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  23392. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  23393. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  23394. return mirrorTexture;
  23395. }
  23396. else if (parsedTexture.isRenderTarget) {
  23397. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  23398. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  23399. return renderTargetTexture;
  23400. }
  23401. else {
  23402. var texture;
  23403. if (parsedTexture.base64String) {
  23404. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  23405. }
  23406. else {
  23407. texture = new Texture(rootUrl + parsedTexture.name, scene, !generateMipMaps);
  23408. }
  23409. return texture;
  23410. }
  23411. }, parsedTexture, scene);
  23412. // Update Sampling Mode
  23413. if (parsedTexture.samplingMode) {
  23414. var sampling = parsedTexture.samplingMode;
  23415. if (texture._samplingMode !== sampling) {
  23416. texture.updateSamplingMode(sampling);
  23417. }
  23418. }
  23419. // Animations
  23420. if (parsedTexture.animations) {
  23421. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  23422. var parsedAnimation = parsedTexture.animations[animationIndex];
  23423. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  23424. }
  23425. }
  23426. return texture;
  23427. };
  23428. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  23429. if (deleteBuffer === void 0) { deleteBuffer = false; }
  23430. if (noMipmap === void 0) { noMipmap = false; }
  23431. if (invertY === void 0) { invertY = true; }
  23432. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  23433. if (onLoad === void 0) { onLoad = null; }
  23434. if (onError === void 0) { onError = null; }
  23435. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  23436. if (name.substr(0, 5) !== "data:") {
  23437. name = "data:" + name;
  23438. }
  23439. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  23440. };
  23441. // Constants
  23442. Texture.NEAREST_SAMPLINGMODE = 1;
  23443. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  23444. Texture.BILINEAR_SAMPLINGMODE = 2;
  23445. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  23446. Texture.TRILINEAR_SAMPLINGMODE = 3;
  23447. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  23448. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  23449. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  23450. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  23451. Texture.NEAREST_LINEAR = 7;
  23452. Texture.NEAREST_NEAREST = 8;
  23453. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  23454. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  23455. Texture.LINEAR_LINEAR = 11;
  23456. Texture.LINEAR_NEAREST = 12;
  23457. Texture.EXPLICIT_MODE = 0;
  23458. Texture.SPHERICAL_MODE = 1;
  23459. Texture.PLANAR_MODE = 2;
  23460. Texture.CUBIC_MODE = 3;
  23461. Texture.PROJECTION_MODE = 4;
  23462. Texture.SKYBOX_MODE = 5;
  23463. Texture.INVCUBIC_MODE = 6;
  23464. Texture.EQUIRECTANGULAR_MODE = 7;
  23465. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  23466. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  23467. Texture.CLAMP_ADDRESSMODE = 0;
  23468. Texture.WRAP_ADDRESSMODE = 1;
  23469. Texture.MIRROR_ADDRESSMODE = 2;
  23470. __decorate([
  23471. BABYLON.serialize()
  23472. ], Texture.prototype, "url", void 0);
  23473. __decorate([
  23474. BABYLON.serialize()
  23475. ], Texture.prototype, "uOffset", void 0);
  23476. __decorate([
  23477. BABYLON.serialize()
  23478. ], Texture.prototype, "vOffset", void 0);
  23479. __decorate([
  23480. BABYLON.serialize()
  23481. ], Texture.prototype, "uScale", void 0);
  23482. __decorate([
  23483. BABYLON.serialize()
  23484. ], Texture.prototype, "vScale", void 0);
  23485. __decorate([
  23486. BABYLON.serialize()
  23487. ], Texture.prototype, "uAng", void 0);
  23488. __decorate([
  23489. BABYLON.serialize()
  23490. ], Texture.prototype, "vAng", void 0);
  23491. __decorate([
  23492. BABYLON.serialize()
  23493. ], Texture.prototype, "wAng", void 0);
  23494. __decorate([
  23495. BABYLON.serialize()
  23496. ], Texture.prototype, "isBlocking", null);
  23497. return Texture;
  23498. }(BABYLON.BaseTexture));
  23499. BABYLON.Texture = Texture;
  23500. })(BABYLON || (BABYLON = {}));
  23501. //# sourceMappingURL=babylon.texture.js.map
  23502. var BABYLON;
  23503. (function (BABYLON) {
  23504. var _InstancesBatch = /** @class */ (function () {
  23505. function _InstancesBatch() {
  23506. this.mustReturn = false;
  23507. this.visibleInstances = new Array();
  23508. this.renderSelf = new Array();
  23509. }
  23510. return _InstancesBatch;
  23511. }());
  23512. BABYLON._InstancesBatch = _InstancesBatch;
  23513. var Mesh = /** @class */ (function (_super) {
  23514. __extends(Mesh, _super);
  23515. /**
  23516. * @constructor
  23517. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  23518. * @param {Scene} scene The scene to add this mesh to.
  23519. * @param {Node} parent The parent of this mesh, if it has one
  23520. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  23521. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  23522. * When false, achieved by calling a clone(), also passing False.
  23523. * This will make creation of children, recursive.
  23524. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  23525. */
  23526. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  23527. if (scene === void 0) { scene = null; }
  23528. if (parent === void 0) { parent = null; }
  23529. if (source === void 0) { source = null; }
  23530. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  23531. var _this = _super.call(this, name, scene) || this;
  23532. // Events
  23533. /**
  23534. * An event triggered before rendering the mesh
  23535. * @type {BABYLON.Observable}
  23536. */
  23537. _this.onBeforeRenderObservable = new BABYLON.Observable();
  23538. /**
  23539. * An event triggered after rendering the mesh
  23540. * @type {BABYLON.Observable}
  23541. */
  23542. _this.onAfterRenderObservable = new BABYLON.Observable();
  23543. /**
  23544. * An event triggered before drawing the mesh
  23545. * @type {BABYLON.Observable}
  23546. */
  23547. _this.onBeforeDrawObservable = new BABYLON.Observable();
  23548. // Members
  23549. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  23550. _this.instances = new Array();
  23551. _this._LODLevels = new Array();
  23552. _this._visibleInstances = {};
  23553. _this._renderIdForInstances = new Array();
  23554. _this._batchCache = new _InstancesBatch();
  23555. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  23556. // Use by builder only to know what orientation were the mesh build in.
  23557. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  23558. _this.overrideMaterialSideOrientation = null;
  23559. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  23560. // Will be used to save a source mesh reference, If any
  23561. _this._source = null;
  23562. scene = _this.getScene();
  23563. if (source) {
  23564. // Source mesh
  23565. _this._source = source;
  23566. // Geometry
  23567. if (source._geometry) {
  23568. source._geometry.applyToMesh(_this);
  23569. }
  23570. // Deep copy
  23571. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId", "source"], ["_poseMatrix", "_source"]);
  23572. // Tags
  23573. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  23574. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  23575. }
  23576. _this.metadata = source.metadata;
  23577. // Parent
  23578. _this.parent = source.parent;
  23579. // Pivot
  23580. _this.setPivotMatrix(source.getPivotMatrix());
  23581. _this.id = name + "." + source.id;
  23582. // Material
  23583. _this.material = source.material;
  23584. var index;
  23585. if (!doNotCloneChildren) {
  23586. // Children
  23587. var directDescendants = source.getDescendants(true);
  23588. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  23589. var child = directDescendants[index_1];
  23590. if (child.clone) {
  23591. child.clone(name + "." + child.name, _this);
  23592. }
  23593. }
  23594. }
  23595. // Physics clone
  23596. var physicsEngine = _this.getScene().getPhysicsEngine();
  23597. if (clonePhysicsImpostor && physicsEngine) {
  23598. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  23599. if (impostor) {
  23600. _this.physicsImpostor = impostor.clone(_this);
  23601. }
  23602. }
  23603. // Particles
  23604. for (index = 0; index < scene.particleSystems.length; index++) {
  23605. var system = scene.particleSystems[index];
  23606. if (system.emitter === source) {
  23607. system.clone(system.name, _this);
  23608. }
  23609. }
  23610. _this.computeWorldMatrix(true);
  23611. }
  23612. // Parent
  23613. if (parent !== null) {
  23614. _this.parent = parent;
  23615. }
  23616. return _this;
  23617. }
  23618. Object.defineProperty(Mesh, "FRONTSIDE", {
  23619. /**
  23620. * Mesh side orientation : usually the external or front surface
  23621. */
  23622. get: function () {
  23623. return Mesh._FRONTSIDE;
  23624. },
  23625. enumerable: true,
  23626. configurable: true
  23627. });
  23628. Object.defineProperty(Mesh, "BACKSIDE", {
  23629. /**
  23630. * Mesh side orientation : usually the internal or back surface
  23631. */
  23632. get: function () {
  23633. return Mesh._BACKSIDE;
  23634. },
  23635. enumerable: true,
  23636. configurable: true
  23637. });
  23638. Object.defineProperty(Mesh, "DOUBLESIDE", {
  23639. /**
  23640. * Mesh side orientation : both internal and external or front and back surfaces
  23641. */
  23642. get: function () {
  23643. return Mesh._DOUBLESIDE;
  23644. },
  23645. enumerable: true,
  23646. configurable: true
  23647. });
  23648. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  23649. /**
  23650. * Mesh side orientation : by default, `FRONTSIDE`
  23651. */
  23652. get: function () {
  23653. return Mesh._DEFAULTSIDE;
  23654. },
  23655. enumerable: true,
  23656. configurable: true
  23657. });
  23658. Object.defineProperty(Mesh, "NO_CAP", {
  23659. /**
  23660. * Mesh cap setting : no cap
  23661. */
  23662. get: function () {
  23663. return Mesh._NO_CAP;
  23664. },
  23665. enumerable: true,
  23666. configurable: true
  23667. });
  23668. Object.defineProperty(Mesh, "CAP_START", {
  23669. /**
  23670. * Mesh cap setting : one cap at the beginning of the mesh
  23671. */
  23672. get: function () {
  23673. return Mesh._CAP_START;
  23674. },
  23675. enumerable: true,
  23676. configurable: true
  23677. });
  23678. Object.defineProperty(Mesh, "CAP_END", {
  23679. /**
  23680. * Mesh cap setting : one cap at the end of the mesh
  23681. */
  23682. get: function () {
  23683. return Mesh._CAP_END;
  23684. },
  23685. enumerable: true,
  23686. configurable: true
  23687. });
  23688. Object.defineProperty(Mesh, "CAP_ALL", {
  23689. /**
  23690. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  23691. */
  23692. get: function () {
  23693. return Mesh._CAP_ALL;
  23694. },
  23695. enumerable: true,
  23696. configurable: true
  23697. });
  23698. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  23699. set: function (callback) {
  23700. if (this._onBeforeDrawObserver) {
  23701. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  23702. }
  23703. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  23704. },
  23705. enumerable: true,
  23706. configurable: true
  23707. });
  23708. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  23709. get: function () {
  23710. return this._morphTargetManager;
  23711. },
  23712. set: function (value) {
  23713. if (this._morphTargetManager === value) {
  23714. return;
  23715. }
  23716. this._morphTargetManager = value;
  23717. this._syncGeometryWithMorphTargetManager();
  23718. },
  23719. enumerable: true,
  23720. configurable: true
  23721. });
  23722. Object.defineProperty(Mesh.prototype, "source", {
  23723. get: function () {
  23724. return this._source;
  23725. },
  23726. enumerable: true,
  23727. configurable: true
  23728. });
  23729. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  23730. get: function () {
  23731. return this._unIndexed;
  23732. },
  23733. set: function (value) {
  23734. if (this._unIndexed !== value) {
  23735. this._unIndexed = value;
  23736. this._markSubMeshesAsAttributesDirty();
  23737. }
  23738. },
  23739. enumerable: true,
  23740. configurable: true
  23741. });
  23742. // Methods
  23743. /**
  23744. * Returns the string "Mesh".
  23745. */
  23746. Mesh.prototype.getClassName = function () {
  23747. return "Mesh";
  23748. };
  23749. /**
  23750. * Returns a string.
  23751. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  23752. */
  23753. Mesh.prototype.toString = function (fullDetails) {
  23754. var ret = _super.prototype.toString.call(this, fullDetails);
  23755. ret += ", n vertices: " + this.getTotalVertices();
  23756. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  23757. if (this.animations) {
  23758. for (var i = 0; i < this.animations.length; i++) {
  23759. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  23760. }
  23761. }
  23762. if (fullDetails) {
  23763. if (this._geometry) {
  23764. var ib = this.getIndices();
  23765. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23766. if (vb && ib) {
  23767. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  23768. }
  23769. }
  23770. else {
  23771. ret += ", flat shading: UNKNOWN";
  23772. }
  23773. }
  23774. return ret;
  23775. };
  23776. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  23777. /**
  23778. * True if the mesh has some Levels Of Details (LOD).
  23779. * Returns a boolean.
  23780. */
  23781. get: function () {
  23782. return this._LODLevels.length > 0;
  23783. },
  23784. enumerable: true,
  23785. configurable: true
  23786. });
  23787. Mesh.prototype._sortLODLevels = function () {
  23788. this._LODLevels.sort(function (a, b) {
  23789. if (a.distance < b.distance) {
  23790. return 1;
  23791. }
  23792. if (a.distance > b.distance) {
  23793. return -1;
  23794. }
  23795. return 0;
  23796. });
  23797. };
  23798. /**
  23799. * Add a mesh as LOD level triggered at the given distance.
  23800. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  23801. * @param {number} distance The distance from the center of the object to show this level
  23802. * @param {Mesh} mesh The mesh to be added as LOD level
  23803. * @return {Mesh} This mesh (for chaining)
  23804. */
  23805. Mesh.prototype.addLODLevel = function (distance, mesh) {
  23806. if (mesh && mesh._masterMesh) {
  23807. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  23808. return this;
  23809. }
  23810. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  23811. this._LODLevels.push(level);
  23812. if (mesh) {
  23813. mesh._masterMesh = this;
  23814. }
  23815. this._sortLODLevels();
  23816. return this;
  23817. };
  23818. /**
  23819. * Returns the LOD level mesh at the passed distance or null if not found.
  23820. * It is related to the method `addLODLevel(distance, mesh)`.
  23821. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  23822. * Returns an object Mesh or `null`.
  23823. */
  23824. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  23825. for (var index = 0; index < this._LODLevels.length; index++) {
  23826. var level = this._LODLevels[index];
  23827. if (level.distance === distance) {
  23828. return level.mesh;
  23829. }
  23830. }
  23831. return null;
  23832. };
  23833. /**
  23834. * Remove a mesh from the LOD array
  23835. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  23836. * @param {Mesh} mesh The mesh to be removed.
  23837. * @return {Mesh} This mesh (for chaining)
  23838. */
  23839. Mesh.prototype.removeLODLevel = function (mesh) {
  23840. for (var index = 0; index < this._LODLevels.length; index++) {
  23841. if (this._LODLevels[index].mesh === mesh) {
  23842. this._LODLevels.splice(index, 1);
  23843. if (mesh) {
  23844. mesh._masterMesh = null;
  23845. }
  23846. }
  23847. }
  23848. this._sortLODLevels();
  23849. return this;
  23850. };
  23851. /**
  23852. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  23853. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  23854. */
  23855. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  23856. if (!this._LODLevels || this._LODLevels.length === 0) {
  23857. return this;
  23858. }
  23859. var bSphere;
  23860. if (boundingSphere) {
  23861. bSphere = boundingSphere;
  23862. }
  23863. else {
  23864. var boundingInfo = this.getBoundingInfo();
  23865. bSphere = boundingInfo.boundingSphere;
  23866. }
  23867. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  23868. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  23869. if (this.onLODLevelSelection) {
  23870. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  23871. }
  23872. return this;
  23873. }
  23874. for (var index = 0; index < this._LODLevels.length; index++) {
  23875. var level = this._LODLevels[index];
  23876. if (level.distance < distanceToCamera) {
  23877. if (level.mesh) {
  23878. level.mesh._preActivate();
  23879. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  23880. }
  23881. if (this.onLODLevelSelection) {
  23882. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  23883. }
  23884. return level.mesh;
  23885. }
  23886. }
  23887. if (this.onLODLevelSelection) {
  23888. this.onLODLevelSelection(distanceToCamera, this, this);
  23889. }
  23890. return this;
  23891. };
  23892. Object.defineProperty(Mesh.prototype, "geometry", {
  23893. /**
  23894. * Returns the mesh internal Geometry object.
  23895. */
  23896. get: function () {
  23897. return this._geometry;
  23898. },
  23899. enumerable: true,
  23900. configurable: true
  23901. });
  23902. /**
  23903. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  23904. */
  23905. Mesh.prototype.getTotalVertices = function () {
  23906. if (this._geometry === null || this._geometry === undefined) {
  23907. return 0;
  23908. }
  23909. return this._geometry.getTotalVertices();
  23910. };
  23911. /**
  23912. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  23913. * 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.
  23914. * You can force the copy with forceCopy === true
  23915. * Returns null if the mesh has no geometry or no vertex buffer.
  23916. * Possible `kind` values :
  23917. * - BABYLON.VertexBuffer.PositionKind
  23918. * - BABYLON.VertexBuffer.UVKind
  23919. * - BABYLON.VertexBuffer.UV2Kind
  23920. * - BABYLON.VertexBuffer.UV3Kind
  23921. * - BABYLON.VertexBuffer.UV4Kind
  23922. * - BABYLON.VertexBuffer.UV5Kind
  23923. * - BABYLON.VertexBuffer.UV6Kind
  23924. * - BABYLON.VertexBuffer.ColorKind
  23925. * - BABYLON.VertexBuffer.MatricesIndicesKind
  23926. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  23927. * - BABYLON.VertexBuffer.MatricesWeightsKind
  23928. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  23929. */
  23930. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  23931. if (!this._geometry) {
  23932. return null;
  23933. }
  23934. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  23935. };
  23936. /**
  23937. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  23938. * Returns `null` if the mesh has no geometry.
  23939. * Possible `kind` values :
  23940. * - BABYLON.VertexBuffer.PositionKind
  23941. * - BABYLON.VertexBuffer.UVKind
  23942. * - BABYLON.VertexBuffer.UV2Kind
  23943. * - BABYLON.VertexBuffer.UV3Kind
  23944. * - BABYLON.VertexBuffer.UV4Kind
  23945. * - BABYLON.VertexBuffer.UV5Kind
  23946. * - BABYLON.VertexBuffer.UV6Kind
  23947. * - BABYLON.VertexBuffer.ColorKind
  23948. * - BABYLON.VertexBuffer.MatricesIndicesKind
  23949. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  23950. * - BABYLON.VertexBuffer.MatricesWeightsKind
  23951. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  23952. */
  23953. Mesh.prototype.getVertexBuffer = function (kind) {
  23954. if (!this._geometry) {
  23955. return null;
  23956. }
  23957. return this._geometry.getVertexBuffer(kind);
  23958. };
  23959. /**
  23960. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  23961. * Possible `kind` values :
  23962. * - BABYLON.VertexBuffer.PositionKind
  23963. * - BABYLON.VertexBuffer.UVKind
  23964. * - BABYLON.VertexBuffer.UV2Kind
  23965. * - BABYLON.VertexBuffer.UV3Kind
  23966. * - BABYLON.VertexBuffer.UV4Kind
  23967. * - BABYLON.VertexBuffer.UV5Kind
  23968. * - BABYLON.VertexBuffer.UV6Kind
  23969. * - BABYLON.VertexBuffer.ColorKind
  23970. * - BABYLON.VertexBuffer.MatricesIndicesKind
  23971. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  23972. * - BABYLON.VertexBuffer.MatricesWeightsKind
  23973. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  23974. */
  23975. Mesh.prototype.isVerticesDataPresent = function (kind) {
  23976. if (!this._geometry) {
  23977. if (this._delayInfo) {
  23978. return this._delayInfo.indexOf(kind) !== -1;
  23979. }
  23980. return false;
  23981. }
  23982. return this._geometry.isVerticesDataPresent(kind);
  23983. };
  23984. /**
  23985. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  23986. * Possible `kind` values :
  23987. * - BABYLON.VertexBuffer.PositionKind
  23988. * - BABYLON.VertexBuffer.UVKind
  23989. * - BABYLON.VertexBuffer.UV2Kind
  23990. * - BABYLON.VertexBuffer.UV3Kind
  23991. * - BABYLON.VertexBuffer.UV4Kind
  23992. * - BABYLON.VertexBuffer.UV5Kind
  23993. * - BABYLON.VertexBuffer.UV6Kind
  23994. * - BABYLON.VertexBuffer.ColorKind
  23995. * - BABYLON.VertexBuffer.MatricesIndicesKind
  23996. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  23997. * - BABYLON.VertexBuffer.MatricesWeightsKind
  23998. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  23999. */
  24000. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  24001. if (!this._geometry) {
  24002. if (this._delayInfo) {
  24003. return this._delayInfo.indexOf(kind) !== -1;
  24004. }
  24005. return false;
  24006. }
  24007. return this._geometry.isVertexBufferUpdatable(kind);
  24008. };
  24009. /**
  24010. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  24011. * Possible `kind` values :
  24012. * - BABYLON.VertexBuffer.PositionKind
  24013. * - BABYLON.VertexBuffer.UVKind
  24014. * - BABYLON.VertexBuffer.UV2Kind
  24015. * - BABYLON.VertexBuffer.UV3Kind
  24016. * - BABYLON.VertexBuffer.UV4Kind
  24017. * - BABYLON.VertexBuffer.UV5Kind
  24018. * - BABYLON.VertexBuffer.UV6Kind
  24019. * - BABYLON.VertexBuffer.ColorKind
  24020. * - BABYLON.VertexBuffer.MatricesIndicesKind
  24021. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  24022. * - BABYLON.VertexBuffer.MatricesWeightsKind
  24023. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  24024. */
  24025. Mesh.prototype.getVerticesDataKinds = function () {
  24026. if (!this._geometry) {
  24027. var result = new Array();
  24028. if (this._delayInfo) {
  24029. this._delayInfo.forEach(function (kind, index, array) {
  24030. result.push(kind);
  24031. });
  24032. }
  24033. return result;
  24034. }
  24035. return this._geometry.getVerticesDataKinds();
  24036. };
  24037. /**
  24038. * Returns a positive integer : the total number of indices in this mesh geometry.
  24039. * Returns zero if the mesh has no geometry.
  24040. */
  24041. Mesh.prototype.getTotalIndices = function () {
  24042. if (!this._geometry) {
  24043. return 0;
  24044. }
  24045. return this._geometry.getTotalIndices();
  24046. };
  24047. /**
  24048. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  24049. * 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.
  24050. * Returns an empty array if the mesh has no geometry.
  24051. */
  24052. Mesh.prototype.getIndices = function (copyWhenShared) {
  24053. if (!this._geometry) {
  24054. return [];
  24055. }
  24056. return this._geometry.getIndices(copyWhenShared);
  24057. };
  24058. Object.defineProperty(Mesh.prototype, "isBlocked", {
  24059. get: function () {
  24060. return this._masterMesh !== null && this._masterMesh !== undefined;
  24061. },
  24062. enumerable: true,
  24063. configurable: true
  24064. });
  24065. /**
  24066. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  24067. */
  24068. Mesh.prototype.isReady = function () {
  24069. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  24070. return false;
  24071. }
  24072. return _super.prototype.isReady.call(this);
  24073. };
  24074. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  24075. /**
  24076. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  24077. * This property is pertinent only for updatable parametric shapes.
  24078. */
  24079. get: function () {
  24080. return this._areNormalsFrozen;
  24081. },
  24082. enumerable: true,
  24083. configurable: true
  24084. });
  24085. /**
  24086. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  24087. * It has no effect at all on other shapes.
  24088. * It prevents the mesh normals from being recomputed on next `positions` array update.
  24089. * Returns the Mesh.
  24090. */
  24091. Mesh.prototype.freezeNormals = function () {
  24092. this._areNormalsFrozen = true;
  24093. return this;
  24094. };
  24095. /**
  24096. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  24097. * It has no effect at all on other shapes.
  24098. * It reactivates the mesh normals computation if it was previously frozen.
  24099. * Returns the Mesh.
  24100. */
  24101. Mesh.prototype.unfreezeNormals = function () {
  24102. this._areNormalsFrozen = false;
  24103. return this;
  24104. };
  24105. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  24106. /**
  24107. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  24108. */
  24109. set: function (count) {
  24110. this._overridenInstanceCount = count;
  24111. },
  24112. enumerable: true,
  24113. configurable: true
  24114. });
  24115. // Methods
  24116. Mesh.prototype._preActivate = function () {
  24117. var sceneRenderId = this.getScene().getRenderId();
  24118. if (this._preActivateId === sceneRenderId) {
  24119. return this;
  24120. }
  24121. this._preActivateId = sceneRenderId;
  24122. this._visibleInstances = null;
  24123. return this;
  24124. };
  24125. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  24126. if (this._visibleInstances) {
  24127. this._visibleInstances.intermediateDefaultRenderId = renderId;
  24128. }
  24129. return this;
  24130. };
  24131. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  24132. if (!this._visibleInstances) {
  24133. this._visibleInstances = {};
  24134. this._visibleInstances.defaultRenderId = renderId;
  24135. this._visibleInstances.selfDefaultRenderId = this._renderId;
  24136. }
  24137. if (!this._visibleInstances[renderId]) {
  24138. this._visibleInstances[renderId] = new Array();
  24139. }
  24140. this._visibleInstances[renderId].push(instance);
  24141. return this;
  24142. };
  24143. /**
  24144. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  24145. * This means the mesh underlying bounding box and sphere are recomputed.
  24146. * Returns the Mesh.
  24147. */
  24148. Mesh.prototype.refreshBoundingInfo = function () {
  24149. return this._refreshBoundingInfo(false);
  24150. };
  24151. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  24152. if (this._boundingInfo && this._boundingInfo.isLocked) {
  24153. return this;
  24154. }
  24155. var data = this._getPositionData(applySkeleton);
  24156. if (data) {
  24157. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  24158. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  24159. }
  24160. if (this.subMeshes) {
  24161. for (var index = 0; index < this.subMeshes.length; index++) {
  24162. this.subMeshes[index].refreshBoundingInfo();
  24163. }
  24164. }
  24165. this._updateBoundingInfo();
  24166. return this;
  24167. };
  24168. Mesh.prototype._getPositionData = function (applySkeleton) {
  24169. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24170. if (data && applySkeleton && this.skeleton) {
  24171. data = data.slice();
  24172. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  24173. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  24174. if (matricesWeightsData && matricesIndicesData) {
  24175. var needExtras = this.numBoneInfluencers > 4;
  24176. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  24177. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  24178. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  24179. var tempVector = BABYLON.Tmp.Vector3[0];
  24180. var finalMatrix = BABYLON.Tmp.Matrix[0];
  24181. var tempMatrix = BABYLON.Tmp.Matrix[1];
  24182. var matWeightIdx = 0;
  24183. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  24184. finalMatrix.reset();
  24185. var inf;
  24186. var weight;
  24187. for (inf = 0; inf < 4; inf++) {
  24188. weight = matricesWeightsData[matWeightIdx + inf];
  24189. if (weight <= 0)
  24190. break;
  24191. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  24192. finalMatrix.addToSelf(tempMatrix);
  24193. }
  24194. if (needExtras) {
  24195. for (inf = 0; inf < 4; inf++) {
  24196. weight = matricesWeightsExtraData[matWeightIdx + inf];
  24197. if (weight <= 0)
  24198. break;
  24199. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  24200. finalMatrix.addToSelf(tempMatrix);
  24201. }
  24202. }
  24203. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  24204. tempVector.toArray(data, index);
  24205. }
  24206. }
  24207. }
  24208. return data;
  24209. };
  24210. Mesh.prototype._createGlobalSubMesh = function (force) {
  24211. var totalVertices = this.getTotalVertices();
  24212. if (!totalVertices || !this.getIndices()) {
  24213. return null;
  24214. }
  24215. // Check if we need to recreate the submeshes
  24216. if (this.subMeshes && this.subMeshes.length > 0) {
  24217. var ib = this.getIndices();
  24218. if (!ib) {
  24219. return null;
  24220. }
  24221. var totalIndices = ib.length;
  24222. var needToRecreate = false;
  24223. if (force) {
  24224. needToRecreate = true;
  24225. }
  24226. else {
  24227. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  24228. var submesh = _a[_i];
  24229. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  24230. needToRecreate = true;
  24231. break;
  24232. }
  24233. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  24234. needToRecreate = true;
  24235. break;
  24236. }
  24237. }
  24238. }
  24239. if (!needToRecreate) {
  24240. return this.subMeshes[0];
  24241. }
  24242. }
  24243. this.releaseSubMeshes();
  24244. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  24245. };
  24246. Mesh.prototype.subdivide = function (count) {
  24247. if (count < 1) {
  24248. return;
  24249. }
  24250. var totalIndices = this.getTotalIndices();
  24251. var subdivisionSize = (totalIndices / count) | 0;
  24252. var offset = 0;
  24253. // Ensure that subdivisionSize is a multiple of 3
  24254. while (subdivisionSize % 3 !== 0) {
  24255. subdivisionSize++;
  24256. }
  24257. this.releaseSubMeshes();
  24258. for (var index = 0; index < count; index++) {
  24259. if (offset >= totalIndices) {
  24260. break;
  24261. }
  24262. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  24263. offset += subdivisionSize;
  24264. }
  24265. this.synchronizeInstances();
  24266. };
  24267. /**
  24268. * Sets the vertex data of the mesh geometry for the requested `kind`.
  24269. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  24270. * The `data` are either a numeric array either a Float32Array.
  24271. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  24272. * 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).
  24273. * Note that a new underlying VertexBuffer object is created each call.
  24274. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  24275. *
  24276. * Possible `kind` values :
  24277. * - BABYLON.VertexBuffer.PositionKind
  24278. * - BABYLON.VertexBuffer.UVKind
  24279. * - BABYLON.VertexBuffer.UV2Kind
  24280. * - BABYLON.VertexBuffer.UV3Kind
  24281. * - BABYLON.VertexBuffer.UV4Kind
  24282. * - BABYLON.VertexBuffer.UV5Kind
  24283. * - BABYLON.VertexBuffer.UV6Kind
  24284. * - BABYLON.VertexBuffer.ColorKind
  24285. * - BABYLON.VertexBuffer.MatricesIndicesKind
  24286. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  24287. * - BABYLON.VertexBuffer.MatricesWeightsKind
  24288. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  24289. *
  24290. * Returns the Mesh.
  24291. */
  24292. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  24293. if (updatable === void 0) { updatable = false; }
  24294. if (!this._geometry) {
  24295. var vertexData = new BABYLON.VertexData();
  24296. vertexData.set(data, kind);
  24297. var scene = this.getScene();
  24298. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  24299. }
  24300. else {
  24301. this._geometry.setVerticesData(kind, data, updatable, stride);
  24302. }
  24303. return this;
  24304. };
  24305. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  24306. if (updatable === void 0) { updatable = true; }
  24307. var vb = this.getVertexBuffer(kind);
  24308. if (!vb || vb.isUpdatable() === updatable) {
  24309. return;
  24310. }
  24311. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  24312. };
  24313. /**
  24314. * Sets the mesh VertexBuffer.
  24315. * Returns the Mesh.
  24316. */
  24317. Mesh.prototype.setVerticesBuffer = function (buffer) {
  24318. if (!this._geometry) {
  24319. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  24320. }
  24321. this._geometry.setVerticesBuffer(buffer);
  24322. return this;
  24323. };
  24324. /**
  24325. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  24326. * If the mesh has no geometry, it is simply returned as it is.
  24327. * The `data` are either a numeric array either a Float32Array.
  24328. * No new underlying VertexBuffer object is created.
  24329. * 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.
  24330. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  24331. *
  24332. * Possible `kind` values :
  24333. * - BABYLON.VertexBuffer.PositionKind
  24334. * - BABYLON.VertexBuffer.UVKind
  24335. * - BABYLON.VertexBuffer.UV2Kind
  24336. * - BABYLON.VertexBuffer.UV3Kind
  24337. * - BABYLON.VertexBuffer.UV4Kind
  24338. * - BABYLON.VertexBuffer.UV5Kind
  24339. * - BABYLON.VertexBuffer.UV6Kind
  24340. * - BABYLON.VertexBuffer.ColorKind
  24341. * - BABYLON.VertexBuffer.MatricesIndicesKind
  24342. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  24343. * - BABYLON.VertexBuffer.MatricesWeightsKind
  24344. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  24345. *
  24346. * Returns the Mesh.
  24347. */
  24348. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  24349. if (!this._geometry) {
  24350. return this;
  24351. }
  24352. if (!makeItUnique) {
  24353. this._geometry.updateVerticesData(kind, data, updateExtends);
  24354. }
  24355. else {
  24356. this.makeGeometryUnique();
  24357. this.updateVerticesData(kind, data, updateExtends, false);
  24358. }
  24359. return this;
  24360. };
  24361. /**
  24362. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  24363. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  24364. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  24365. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  24366. * Returns the Mesh.
  24367. */
  24368. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  24369. if (computeNormals === void 0) { computeNormals = true; }
  24370. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24371. if (!positions) {
  24372. return this;
  24373. }
  24374. positionFunction(positions);
  24375. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  24376. if (computeNormals) {
  24377. var indices = this.getIndices();
  24378. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  24379. if (!normals) {
  24380. return this;
  24381. }
  24382. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  24383. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  24384. }
  24385. return this;
  24386. };
  24387. /**
  24388. * Creates a un-shared specific occurence of the geometry for the mesh.
  24389. * Returns the Mesh.
  24390. */
  24391. Mesh.prototype.makeGeometryUnique = function () {
  24392. if (!this._geometry) {
  24393. return this;
  24394. }
  24395. var oldGeometry = this._geometry;
  24396. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  24397. oldGeometry.releaseForMesh(this, true);
  24398. geometry.applyToMesh(this);
  24399. return this;
  24400. };
  24401. /**
  24402. * Sets the mesh indices.
  24403. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  24404. * Type is Uint16Array by default unless the mesh has more than 65536 vertices.
  24405. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  24406. * This method creates a new index buffer each call.
  24407. * Returns the Mesh.
  24408. */
  24409. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  24410. if (totalVertices === void 0) { totalVertices = null; }
  24411. if (updatable === void 0) { updatable = false; }
  24412. if (!this._geometry) {
  24413. var vertexData = new BABYLON.VertexData();
  24414. vertexData.indices = indices;
  24415. var scene = this.getScene();
  24416. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  24417. }
  24418. else {
  24419. this._geometry.setIndices(indices, totalVertices, updatable);
  24420. }
  24421. return this;
  24422. };
  24423. /**
  24424. * Update the current index buffer
  24425. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  24426. * Returns the Mesh.
  24427. */
  24428. Mesh.prototype.updateIndices = function (indices, offset) {
  24429. if (!this._geometry) {
  24430. return this;
  24431. }
  24432. this._geometry.updateIndices(indices, offset);
  24433. return this;
  24434. };
  24435. /**
  24436. * Invert the geometry to move from a right handed system to a left handed one.
  24437. * Returns the Mesh.
  24438. */
  24439. Mesh.prototype.toLeftHanded = function () {
  24440. if (!this._geometry) {
  24441. return this;
  24442. }
  24443. this._geometry.toLeftHanded();
  24444. return this;
  24445. };
  24446. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  24447. if (!this._geometry) {
  24448. return this;
  24449. }
  24450. var engine = this.getScene().getEngine();
  24451. // Wireframe
  24452. var indexToBind;
  24453. if (this._unIndexed) {
  24454. indexToBind = null;
  24455. }
  24456. else {
  24457. switch (fillMode) {
  24458. case BABYLON.Material.PointFillMode:
  24459. indexToBind = null;
  24460. break;
  24461. case BABYLON.Material.WireFrameFillMode:
  24462. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  24463. break;
  24464. default:
  24465. case BABYLON.Material.TriangleFillMode:
  24466. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  24467. break;
  24468. }
  24469. }
  24470. // VBOs
  24471. this._geometry._bind(effect, indexToBind);
  24472. return this;
  24473. };
  24474. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  24475. if (alternate === void 0) { alternate = false; }
  24476. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  24477. return this;
  24478. }
  24479. this.onBeforeDrawObservable.notifyObservers(this);
  24480. var scene = this.getScene();
  24481. var engine = scene.getEngine();
  24482. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  24483. // or triangles as points
  24484. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  24485. }
  24486. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  24487. // Triangles as wireframe
  24488. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  24489. }
  24490. else {
  24491. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  24492. }
  24493. if (scene._isAlternateRenderingEnabled && !alternate) {
  24494. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  24495. if (!effect || !scene.activeCamera) {
  24496. return this;
  24497. }
  24498. scene._switchToAlternateCameraConfiguration(true);
  24499. this._effectiveMaterial.bindView(effect);
  24500. this._effectiveMaterial.bindViewProjection(effect);
  24501. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  24502. this._draw(subMesh, fillMode, instancesCount, true);
  24503. engine.setViewport(scene.activeCamera.viewport);
  24504. scene._switchToAlternateCameraConfiguration(false);
  24505. this._effectiveMaterial.bindView(effect);
  24506. this._effectiveMaterial.bindViewProjection(effect);
  24507. }
  24508. return this;
  24509. };
  24510. /**
  24511. * Registers for this mesh a javascript function called just before the rendering process.
  24512. * This function is passed the current mesh.
  24513. * Return the Mesh.
  24514. */
  24515. Mesh.prototype.registerBeforeRender = function (func) {
  24516. this.onBeforeRenderObservable.add(func);
  24517. return this;
  24518. };
  24519. /**
  24520. * Disposes a previously registered javascript function called before the rendering.
  24521. * This function is passed the current mesh.
  24522. * Returns the Mesh.
  24523. */
  24524. Mesh.prototype.unregisterBeforeRender = function (func) {
  24525. this.onBeforeRenderObservable.removeCallback(func);
  24526. return this;
  24527. };
  24528. /**
  24529. * Registers for this mesh a javascript function called just after the rendering is complete.
  24530. * This function is passed the current mesh.
  24531. * Returns the Mesh.
  24532. */
  24533. Mesh.prototype.registerAfterRender = function (func) {
  24534. this.onAfterRenderObservable.add(func);
  24535. return this;
  24536. };
  24537. /**
  24538. * Disposes a previously registered javascript function called after the rendering.
  24539. * This function is passed the current mesh.
  24540. * Return the Mesh.
  24541. */
  24542. Mesh.prototype.unregisterAfterRender = function (func) {
  24543. this.onAfterRenderObservable.removeCallback(func);
  24544. return this;
  24545. };
  24546. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  24547. var scene = this.getScene();
  24548. this._batchCache.mustReturn = false;
  24549. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  24550. this._batchCache.visibleInstances[subMeshId] = null;
  24551. if (this._visibleInstances) {
  24552. var currentRenderId = scene.getRenderId();
  24553. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  24554. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  24555. var selfRenderId = this._renderId;
  24556. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  24557. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  24558. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  24559. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  24560. }
  24561. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  24562. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  24563. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  24564. this._batchCache.mustReturn = true;
  24565. return this._batchCache;
  24566. }
  24567. if (currentRenderId !== selfRenderId) {
  24568. this._batchCache.renderSelf[subMeshId] = false;
  24569. }
  24570. }
  24571. this._renderIdForInstances[subMeshId] = currentRenderId;
  24572. }
  24573. return this._batchCache;
  24574. };
  24575. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  24576. var visibleInstances = batch.visibleInstances[subMesh._id];
  24577. if (!visibleInstances) {
  24578. return this;
  24579. }
  24580. var matricesCount = visibleInstances.length + 1;
  24581. var bufferSize = matricesCount * 16 * 4;
  24582. var currentInstancesBufferSize = this._instancesBufferSize;
  24583. var instancesBuffer = this._instancesBuffer;
  24584. while (this._instancesBufferSize < bufferSize) {
  24585. this._instancesBufferSize *= 2;
  24586. }
  24587. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  24588. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  24589. }
  24590. var offset = 0;
  24591. var instancesCount = 0;
  24592. var world = this.getWorldMatrix();
  24593. if (batch.renderSelf[subMesh._id]) {
  24594. world.copyToArray(this._instancesData, offset);
  24595. offset += 16;
  24596. instancesCount++;
  24597. }
  24598. if (visibleInstances) {
  24599. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  24600. var instance = visibleInstances[instanceIndex];
  24601. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  24602. offset += 16;
  24603. instancesCount++;
  24604. }
  24605. }
  24606. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  24607. if (instancesBuffer) {
  24608. instancesBuffer.dispose();
  24609. }
  24610. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  24611. this._instancesBuffer = instancesBuffer;
  24612. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  24613. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  24614. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  24615. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  24616. }
  24617. else {
  24618. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  24619. }
  24620. this._bind(subMesh, effect, fillMode);
  24621. this._draw(subMesh, fillMode, instancesCount);
  24622. engine.unbindInstanceAttributes();
  24623. return this;
  24624. };
  24625. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  24626. var scene = this.getScene();
  24627. var engine = scene.getEngine();
  24628. if (hardwareInstancedRendering) {
  24629. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  24630. }
  24631. else {
  24632. if (batch.renderSelf[subMesh._id]) {
  24633. // Draw
  24634. if (onBeforeDraw) {
  24635. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  24636. }
  24637. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  24638. }
  24639. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  24640. if (visibleInstancesForSubMesh) {
  24641. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  24642. var instance = visibleInstancesForSubMesh[instanceIndex];
  24643. // World
  24644. var world = instance.getWorldMatrix();
  24645. if (onBeforeDraw) {
  24646. onBeforeDraw(true, world, effectiveMaterial);
  24647. }
  24648. // Draw
  24649. this._draw(subMesh, fillMode);
  24650. }
  24651. }
  24652. }
  24653. return this;
  24654. };
  24655. /**
  24656. * Triggers the draw call for the mesh.
  24657. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  24658. * Returns the Mesh.
  24659. */
  24660. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  24661. this.checkOcclusionQuery();
  24662. if (this._isOccluded) {
  24663. return this;
  24664. }
  24665. var scene = this.getScene();
  24666. // Managing instances
  24667. var batch = this._getInstancesRenderList(subMesh._id);
  24668. if (batch.mustReturn) {
  24669. return this;
  24670. }
  24671. // Checking geometry state
  24672. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  24673. return this;
  24674. }
  24675. this.onBeforeRenderObservable.notifyObservers(this);
  24676. var engine = scene.getEngine();
  24677. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  24678. // Material
  24679. var material = subMesh.getMaterial();
  24680. if (!material) {
  24681. return this;
  24682. }
  24683. this._effectiveMaterial = material;
  24684. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  24685. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  24686. return this;
  24687. }
  24688. }
  24689. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  24690. return this;
  24691. }
  24692. // Alpha mode
  24693. if (enableAlphaMode) {
  24694. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  24695. }
  24696. // Outline - step 1
  24697. var savedDepthWrite = engine.getDepthWrite();
  24698. if (this.renderOutline) {
  24699. engine.setDepthWrite(false);
  24700. scene.getOutlineRenderer().render(subMesh, batch);
  24701. engine.setDepthWrite(savedDepthWrite);
  24702. }
  24703. var effect;
  24704. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  24705. effect = subMesh.effect;
  24706. }
  24707. else {
  24708. effect = this._effectiveMaterial.getEffect();
  24709. }
  24710. if (!effect) {
  24711. return this;
  24712. }
  24713. var sideOrientation = this.overrideMaterialSideOrientation;
  24714. if (sideOrientation == null) {
  24715. sideOrientation = this._effectiveMaterial.sideOrientation;
  24716. if (this._getWorldMatrixDeterminant() < 0) {
  24717. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  24718. }
  24719. }
  24720. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  24721. if (this._effectiveMaterial.forceDepthWrite) {
  24722. engine.setDepthWrite(true);
  24723. }
  24724. // Bind
  24725. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  24726. if (!hardwareInstancedRendering) {
  24727. this._bind(subMesh, effect, fillMode);
  24728. }
  24729. var world = this.getWorldMatrix();
  24730. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  24731. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  24732. }
  24733. else {
  24734. this._effectiveMaterial.bind(world, this);
  24735. }
  24736. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  24737. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  24738. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  24739. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  24740. }
  24741. // Draw
  24742. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  24743. // Unbind
  24744. this._effectiveMaterial.unbind();
  24745. // Outline - step 2
  24746. if (this.renderOutline && savedDepthWrite) {
  24747. engine.setDepthWrite(true);
  24748. engine.setColorWrite(false);
  24749. scene.getOutlineRenderer().render(subMesh, batch);
  24750. engine.setColorWrite(true);
  24751. }
  24752. // Overlay
  24753. if (this.renderOverlay) {
  24754. var currentMode = engine.getAlphaMode();
  24755. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  24756. scene.getOutlineRenderer().render(subMesh, batch, true);
  24757. engine.setAlphaMode(currentMode);
  24758. }
  24759. this.onAfterRenderObservable.notifyObservers(this);
  24760. return this;
  24761. };
  24762. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  24763. if (isInstance && effectiveMaterial) {
  24764. effectiveMaterial.bindOnlyWorldMatrix(world);
  24765. }
  24766. };
  24767. /**
  24768. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  24769. */
  24770. Mesh.prototype.getEmittedParticleSystems = function () {
  24771. var results = new Array();
  24772. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  24773. var particleSystem = this.getScene().particleSystems[index];
  24774. if (particleSystem.emitter === this) {
  24775. results.push(particleSystem);
  24776. }
  24777. }
  24778. return results;
  24779. };
  24780. /**
  24781. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  24782. */
  24783. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  24784. var results = new Array();
  24785. var descendants = this.getDescendants();
  24786. descendants.push(this);
  24787. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  24788. var particleSystem = this.getScene().particleSystems[index];
  24789. var emitter = particleSystem.emitter;
  24790. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  24791. results.push(particleSystem);
  24792. }
  24793. }
  24794. return results;
  24795. };
  24796. Mesh.prototype._checkDelayState = function () {
  24797. var scene = this.getScene();
  24798. if (this._geometry) {
  24799. this._geometry.load(scene);
  24800. }
  24801. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  24802. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  24803. this._queueLoad(scene);
  24804. }
  24805. return this;
  24806. };
  24807. Mesh.prototype._queueLoad = function (scene) {
  24808. var _this = this;
  24809. scene._addPendingData(this);
  24810. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  24811. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  24812. if (data instanceof ArrayBuffer) {
  24813. _this._delayLoadingFunction(data, _this);
  24814. }
  24815. else {
  24816. _this._delayLoadingFunction(JSON.parse(data), _this);
  24817. }
  24818. _this.instances.forEach(function (instance) {
  24819. instance._syncSubMeshes();
  24820. });
  24821. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  24822. scene._removePendingData(_this);
  24823. }, function () { }, scene.database, getBinaryData);
  24824. return this;
  24825. };
  24826. /**
  24827. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  24828. */
  24829. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  24830. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  24831. return false;
  24832. }
  24833. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  24834. return false;
  24835. }
  24836. this._checkDelayState();
  24837. return true;
  24838. };
  24839. /**
  24840. * Sets the mesh material by the material or multiMaterial `id` property.
  24841. * The material `id` is a string identifying the material or the multiMaterial.
  24842. * This method returns the Mesh.
  24843. */
  24844. Mesh.prototype.setMaterialByID = function (id) {
  24845. var materials = this.getScene().materials;
  24846. var index;
  24847. for (index = materials.length - 1; index > -1; index--) {
  24848. if (materials[index].id === id) {
  24849. this.material = materials[index];
  24850. return this;
  24851. }
  24852. }
  24853. // Multi
  24854. var multiMaterials = this.getScene().multiMaterials;
  24855. for (index = multiMaterials.length - 1; index > -1; index--) {
  24856. if (multiMaterials[index].id === id) {
  24857. this.material = multiMaterials[index];
  24858. return this;
  24859. }
  24860. }
  24861. return this;
  24862. };
  24863. /**
  24864. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  24865. */
  24866. Mesh.prototype.getAnimatables = function () {
  24867. var results = new Array();
  24868. if (this.material) {
  24869. results.push(this.material);
  24870. }
  24871. if (this.skeleton) {
  24872. results.push(this.skeleton);
  24873. }
  24874. return results;
  24875. };
  24876. /**
  24877. * Modifies the mesh geometry according to the passed transformation matrix.
  24878. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  24879. * The mesh normals are modified accordingly the same transformation.
  24880. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  24881. * Note that, under the hood, this method sets a new VertexBuffer each call.
  24882. * Returns the Mesh.
  24883. */
  24884. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  24885. // Position
  24886. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  24887. return this;
  24888. }
  24889. var submeshes = this.subMeshes.splice(0);
  24890. this._resetPointsArrayCache();
  24891. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24892. var temp = new Array();
  24893. var index;
  24894. for (index = 0; index < data.length; index += 3) {
  24895. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  24896. }
  24897. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  24898. // Normals
  24899. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  24900. return this;
  24901. }
  24902. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  24903. temp = [];
  24904. for (index = 0; index < data.length; index += 3) {
  24905. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  24906. }
  24907. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  24908. // flip faces?
  24909. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  24910. this.flipFaces();
  24911. }
  24912. // Restore submeshes
  24913. this.releaseSubMeshes();
  24914. this.subMeshes = submeshes;
  24915. return this;
  24916. };
  24917. /**
  24918. * Modifies the mesh geometry according to its own current World Matrix.
  24919. * The mesh World Matrix is then reset.
  24920. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  24921. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  24922. * Note that, under the hood, this method sets a new VertexBuffer each call.
  24923. * Returns the Mesh.
  24924. */
  24925. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  24926. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  24927. this.scaling.copyFromFloats(1, 1, 1);
  24928. this.position.copyFromFloats(0, 0, 0);
  24929. this.rotation.copyFromFloats(0, 0, 0);
  24930. //only if quaternion is already set
  24931. if (this.rotationQuaternion) {
  24932. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  24933. }
  24934. this._worldMatrix = BABYLON.Matrix.Identity();
  24935. return this;
  24936. };
  24937. Object.defineProperty(Mesh.prototype, "_positions", {
  24938. // Cache
  24939. get: function () {
  24940. if (this._geometry) {
  24941. return this._geometry._positions;
  24942. }
  24943. return null;
  24944. },
  24945. enumerable: true,
  24946. configurable: true
  24947. });
  24948. Mesh.prototype._resetPointsArrayCache = function () {
  24949. if (this._geometry) {
  24950. this._geometry._resetPointsArrayCache();
  24951. }
  24952. return this;
  24953. };
  24954. Mesh.prototype._generatePointsArray = function () {
  24955. if (this._geometry) {
  24956. return this._geometry._generatePointsArray();
  24957. }
  24958. return false;
  24959. };
  24960. /**
  24961. * Returns a new Mesh object generated from the current mesh properties.
  24962. * This method must not get confused with createInstance().
  24963. * The parameter `name` is a string, the name given to the new mesh.
  24964. * The optional parameter `newParent` can be any Node object (default `null`).
  24965. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  24966. * 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.
  24967. */
  24968. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  24969. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  24970. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  24971. };
  24972. /**
  24973. * Disposes the Mesh.
  24974. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  24975. * Returns nothing.
  24976. */
  24977. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  24978. var _this = this;
  24979. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  24980. this.morphTargetManager = null;
  24981. if (this._geometry) {
  24982. this._geometry.releaseForMesh(this, true);
  24983. }
  24984. // Sources
  24985. var meshes = this.getScene().meshes;
  24986. meshes.forEach(function (abstractMesh) {
  24987. var mesh = abstractMesh;
  24988. if (mesh._source && mesh._source === _this) {
  24989. mesh._source = null;
  24990. }
  24991. });
  24992. this._source = null;
  24993. // Instances
  24994. if (this._instancesBuffer) {
  24995. this._instancesBuffer.dispose();
  24996. this._instancesBuffer = null;
  24997. }
  24998. while (this.instances.length) {
  24999. this.instances[0].dispose();
  25000. }
  25001. // Highlight layers.
  25002. var highlightLayers = this.getScene().highlightLayers;
  25003. for (var i = 0; i < highlightLayers.length; i++) {
  25004. var highlightLayer = highlightLayers[i];
  25005. if (highlightLayer) {
  25006. highlightLayer.removeMesh(this);
  25007. highlightLayer.removeExcludedMesh(this);
  25008. }
  25009. }
  25010. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  25011. };
  25012. /**
  25013. * Modifies the mesh geometry according to a displacement map.
  25014. * 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.
  25015. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  25016. * This method returns nothing.
  25017. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  25018. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  25019. * 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.
  25020. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  25021. * The parameter `uvScale` is an optional vector2 used to scale UV.
  25022. *
  25023. * Returns the Mesh.
  25024. */
  25025. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  25026. var _this = this;
  25027. var scene = this.getScene();
  25028. var onload = function (img) {
  25029. // Getting height map data
  25030. var canvas = document.createElement("canvas");
  25031. var context = canvas.getContext("2d");
  25032. var heightMapWidth = img.width;
  25033. var heightMapHeight = img.height;
  25034. canvas.width = heightMapWidth;
  25035. canvas.height = heightMapHeight;
  25036. context.drawImage(img, 0, 0);
  25037. // Create VertexData from map data
  25038. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  25039. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  25040. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  25041. //execute success callback, if set
  25042. if (onSuccess) {
  25043. onSuccess(_this);
  25044. }
  25045. };
  25046. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  25047. return this;
  25048. };
  25049. /**
  25050. * Modifies the mesh geometry according to a displacementMap buffer.
  25051. * 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.
  25052. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  25053. * This method returns nothing.
  25054. * 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.
  25055. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  25056. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  25057. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  25058. * The parameter `uvScale` is an optional vector2 used to scale UV.
  25059. *
  25060. * Returns the Mesh.
  25061. */
  25062. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  25063. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  25064. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  25065. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  25066. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  25067. return this;
  25068. }
  25069. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25070. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  25071. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  25072. var position = BABYLON.Vector3.Zero();
  25073. var normal = BABYLON.Vector3.Zero();
  25074. var uv = BABYLON.Vector2.Zero();
  25075. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  25076. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  25077. for (var index = 0; index < positions.length; index += 3) {
  25078. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  25079. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  25080. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  25081. // Compute height
  25082. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  25083. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  25084. var pos = (u + v * heightMapWidth) * 4;
  25085. var r = buffer[pos] / 255.0;
  25086. var g = buffer[pos + 1] / 255.0;
  25087. var b = buffer[pos + 2] / 255.0;
  25088. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  25089. normal.normalize();
  25090. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  25091. position = position.add(normal);
  25092. position.toArray(positions, index);
  25093. }
  25094. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  25095. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  25096. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  25097. return this;
  25098. };
  25099. /**
  25100. * Modify the mesh to get a flat shading rendering.
  25101. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  25102. * This method returns the Mesh.
  25103. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  25104. */
  25105. Mesh.prototype.convertToFlatShadedMesh = function () {
  25106. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  25107. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  25108. var kinds = this.getVerticesDataKinds();
  25109. var vbs = {};
  25110. var data = {};
  25111. var newdata = {};
  25112. var updatableNormals = false;
  25113. var kindIndex;
  25114. var kind;
  25115. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  25116. kind = kinds[kindIndex];
  25117. var vertexBuffer = this.getVertexBuffer(kind);
  25118. if (kind === BABYLON.VertexBuffer.NormalKind) {
  25119. updatableNormals = vertexBuffer.isUpdatable();
  25120. kinds.splice(kindIndex, 1);
  25121. kindIndex--;
  25122. continue;
  25123. }
  25124. vbs[kind] = vertexBuffer;
  25125. data[kind] = vbs[kind].getData();
  25126. newdata[kind] = [];
  25127. }
  25128. // Save previous submeshes
  25129. var previousSubmeshes = this.subMeshes.slice(0);
  25130. var indices = this.getIndices();
  25131. var totalIndices = this.getTotalIndices();
  25132. // Generating unique vertices per face
  25133. var index;
  25134. for (index = 0; index < totalIndices; index++) {
  25135. var vertexIndex = indices[index];
  25136. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  25137. kind = kinds[kindIndex];
  25138. var stride = vbs[kind].getStrideSize();
  25139. for (var offset = 0; offset < stride; offset++) {
  25140. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  25141. }
  25142. }
  25143. }
  25144. // Updating faces & normal
  25145. var normals = [];
  25146. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  25147. for (index = 0; index < totalIndices; index += 3) {
  25148. indices[index] = index;
  25149. indices[index + 1] = index + 1;
  25150. indices[index + 2] = index + 2;
  25151. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  25152. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  25153. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  25154. var p1p2 = p1.subtract(p2);
  25155. var p3p2 = p3.subtract(p2);
  25156. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  25157. // Store same normals for every vertex
  25158. for (var localIndex = 0; localIndex < 3; localIndex++) {
  25159. normals.push(normal.x);
  25160. normals.push(normal.y);
  25161. normals.push(normal.z);
  25162. }
  25163. }
  25164. this.setIndices(indices);
  25165. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  25166. // Updating vertex buffers
  25167. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  25168. kind = kinds[kindIndex];
  25169. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  25170. }
  25171. // Updating submeshes
  25172. this.releaseSubMeshes();
  25173. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  25174. var previousOne = previousSubmeshes[submeshIndex];
  25175. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  25176. }
  25177. this.synchronizeInstances();
  25178. return this;
  25179. };
  25180. /**
  25181. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  25182. * In other words, more vertices, no more indices and a single bigger VBO.
  25183. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  25184. * Returns the Mesh.
  25185. */
  25186. Mesh.prototype.convertToUnIndexedMesh = function () {
  25187. /// <summary>Remove indices by unfolding faces into buffers</summary>
  25188. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  25189. var kinds = this.getVerticesDataKinds();
  25190. var vbs = {};
  25191. var data = {};
  25192. var newdata = {};
  25193. var kindIndex;
  25194. var kind;
  25195. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  25196. kind = kinds[kindIndex];
  25197. var vertexBuffer = this.getVertexBuffer(kind);
  25198. vbs[kind] = vertexBuffer;
  25199. data[kind] = vbs[kind].getData();
  25200. newdata[kind] = [];
  25201. }
  25202. // Save previous submeshes
  25203. var previousSubmeshes = this.subMeshes.slice(0);
  25204. var indices = this.getIndices();
  25205. var totalIndices = this.getTotalIndices();
  25206. // Generating unique vertices per face
  25207. var index;
  25208. for (index = 0; index < totalIndices; index++) {
  25209. var vertexIndex = indices[index];
  25210. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  25211. kind = kinds[kindIndex];
  25212. var stride = vbs[kind].getStrideSize();
  25213. for (var offset = 0; offset < stride; offset++) {
  25214. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  25215. }
  25216. }
  25217. }
  25218. // Updating indices
  25219. for (index = 0; index < totalIndices; index += 3) {
  25220. indices[index] = index;
  25221. indices[index + 1] = index + 1;
  25222. indices[index + 2] = index + 2;
  25223. }
  25224. this.setIndices(indices);
  25225. // Updating vertex buffers
  25226. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  25227. kind = kinds[kindIndex];
  25228. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  25229. }
  25230. // Updating submeshes
  25231. this.releaseSubMeshes();
  25232. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  25233. var previousOne = previousSubmeshes[submeshIndex];
  25234. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  25235. }
  25236. this._unIndexed = true;
  25237. this.synchronizeInstances();
  25238. return this;
  25239. };
  25240. /**
  25241. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  25242. * This method returns the Mesh.
  25243. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  25244. */
  25245. Mesh.prototype.flipFaces = function (flipNormals) {
  25246. if (flipNormals === void 0) { flipNormals = false; }
  25247. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  25248. var i;
  25249. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  25250. for (i = 0; i < vertex_data.normals.length; i++) {
  25251. vertex_data.normals[i] *= -1;
  25252. }
  25253. }
  25254. if (vertex_data.indices) {
  25255. var temp;
  25256. for (i = 0; i < vertex_data.indices.length; i += 3) {
  25257. // reassign indices
  25258. temp = vertex_data.indices[i + 1];
  25259. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  25260. vertex_data.indices[i + 2] = temp;
  25261. }
  25262. }
  25263. vertex_data.applyToMesh(this);
  25264. return this;
  25265. };
  25266. // Instances
  25267. /**
  25268. * Creates a new InstancedMesh object from the mesh model.
  25269. * An instance shares the same properties and the same material than its model.
  25270. * Only these properties of each instance can then be set individually :
  25271. * - position
  25272. * - rotation
  25273. * - rotationQuaternion
  25274. * - setPivotMatrix
  25275. * - scaling
  25276. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  25277. * Warning : this method is not supported for Line mesh and LineSystem
  25278. */
  25279. Mesh.prototype.createInstance = function (name) {
  25280. return new BABYLON.InstancedMesh(name, this);
  25281. };
  25282. /**
  25283. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  25284. * After this call, all the mesh instances have the same submeshes than the current mesh.
  25285. * This method returns the Mesh.
  25286. */
  25287. Mesh.prototype.synchronizeInstances = function () {
  25288. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  25289. var instance = this.instances[instanceIndex];
  25290. instance._syncSubMeshes();
  25291. }
  25292. return this;
  25293. };
  25294. /**
  25295. * Simplify the mesh according to the given array of settings.
  25296. * Function will return immediately and will simplify async. It returns the Mesh.
  25297. * @param settings a collection of simplification settings.
  25298. * @param parallelProcessing should all levels calculate parallel or one after the other.
  25299. * @param type the type of simplification to run.
  25300. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  25301. */
  25302. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  25303. if (parallelProcessing === void 0) { parallelProcessing = true; }
  25304. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  25305. this.getScene().simplificationQueue.addTask({
  25306. settings: settings,
  25307. parallelProcessing: parallelProcessing,
  25308. mesh: this,
  25309. simplificationType: simplificationType,
  25310. successCallback: successCallback
  25311. });
  25312. return this;
  25313. };
  25314. /**
  25315. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  25316. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  25317. * This should be used together with the simplification to avoid disappearing triangles.
  25318. * Returns the Mesh.
  25319. * @param successCallback an optional success callback to be called after the optimization finished.
  25320. */
  25321. Mesh.prototype.optimizeIndices = function (successCallback) {
  25322. var _this = this;
  25323. var indices = this.getIndices();
  25324. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25325. if (!positions || !indices) {
  25326. return this;
  25327. }
  25328. var vectorPositions = new Array();
  25329. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  25330. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  25331. }
  25332. var dupes = new Array();
  25333. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  25334. var realPos = vectorPositions.length - 1 - iteration;
  25335. var testedPosition = vectorPositions[realPos];
  25336. for (var j = 0; j < realPos; ++j) {
  25337. var againstPosition = vectorPositions[j];
  25338. if (testedPosition.equals(againstPosition)) {
  25339. dupes[realPos] = j;
  25340. break;
  25341. }
  25342. }
  25343. }, function () {
  25344. for (var i = 0; i < indices.length; ++i) {
  25345. indices[i] = dupes[indices[i]] || indices[i];
  25346. }
  25347. //indices are now reordered
  25348. var originalSubMeshes = _this.subMeshes.slice(0);
  25349. _this.setIndices(indices);
  25350. _this.subMeshes = originalSubMeshes;
  25351. if (successCallback) {
  25352. successCallback(_this);
  25353. }
  25354. });
  25355. return this;
  25356. };
  25357. Mesh.prototype.serialize = function (serializationObject) {
  25358. serializationObject.name = this.name;
  25359. serializationObject.id = this.id;
  25360. serializationObject.type = this.getClassName();
  25361. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  25362. serializationObject.tags = BABYLON.Tags.GetTags(this);
  25363. }
  25364. serializationObject.position = this.position.asArray();
  25365. if (this.rotationQuaternion) {
  25366. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  25367. }
  25368. else if (this.rotation) {
  25369. serializationObject.rotation = this.rotation.asArray();
  25370. }
  25371. serializationObject.scaling = this.scaling.asArray();
  25372. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  25373. serializationObject.isEnabled = this.isEnabled(false);
  25374. serializationObject.isVisible = this.isVisible;
  25375. serializationObject.infiniteDistance = this.infiniteDistance;
  25376. serializationObject.pickable = this.isPickable;
  25377. serializationObject.receiveShadows = this.receiveShadows;
  25378. serializationObject.billboardMode = this.billboardMode;
  25379. serializationObject.visibility = this.visibility;
  25380. serializationObject.checkCollisions = this.checkCollisions;
  25381. serializationObject.isBlocker = this.isBlocker;
  25382. // Parent
  25383. if (this.parent) {
  25384. serializationObject.parentId = this.parent.id;
  25385. }
  25386. // Geometry
  25387. serializationObject.isUnIndexed = this.isUnIndexed;
  25388. var geometry = this._geometry;
  25389. if (geometry) {
  25390. var geometryId = geometry.id;
  25391. serializationObject.geometryId = geometryId;
  25392. // SubMeshes
  25393. serializationObject.subMeshes = [];
  25394. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  25395. var subMesh = this.subMeshes[subIndex];
  25396. serializationObject.subMeshes.push({
  25397. materialIndex: subMesh.materialIndex,
  25398. verticesStart: subMesh.verticesStart,
  25399. verticesCount: subMesh.verticesCount,
  25400. indexStart: subMesh.indexStart,
  25401. indexCount: subMesh.indexCount
  25402. });
  25403. }
  25404. }
  25405. // Material
  25406. if (this.material) {
  25407. serializationObject.materialId = this.material.id;
  25408. }
  25409. else {
  25410. this.material = null;
  25411. }
  25412. // Morph targets
  25413. if (this.morphTargetManager) {
  25414. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  25415. }
  25416. // Skeleton
  25417. if (this.skeleton) {
  25418. serializationObject.skeletonId = this.skeleton.id;
  25419. }
  25420. // Physics
  25421. //TODO implement correct serialization for physics impostors.
  25422. var impostor = this.getPhysicsImpostor();
  25423. if (impostor) {
  25424. serializationObject.physicsMass = impostor.getParam("mass");
  25425. serializationObject.physicsFriction = impostor.getParam("friction");
  25426. serializationObject.physicsRestitution = impostor.getParam("mass");
  25427. serializationObject.physicsImpostor = impostor.type;
  25428. }
  25429. // Metadata
  25430. if (this.metadata) {
  25431. serializationObject.metadata = this.metadata;
  25432. }
  25433. // Instances
  25434. serializationObject.instances = [];
  25435. for (var index = 0; index < this.instances.length; index++) {
  25436. var instance = this.instances[index];
  25437. var serializationInstance = {
  25438. name: instance.name,
  25439. id: instance.id,
  25440. position: instance.position.asArray(),
  25441. scaling: instance.scaling.asArray()
  25442. };
  25443. if (instance.rotationQuaternion) {
  25444. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  25445. }
  25446. else if (instance.rotation) {
  25447. serializationInstance.rotation = instance.rotation.asArray();
  25448. }
  25449. serializationObject.instances.push(serializationInstance);
  25450. // Animations
  25451. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  25452. serializationInstance.ranges = instance.serializeAnimationRanges();
  25453. }
  25454. //
  25455. // Animations
  25456. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  25457. serializationObject.ranges = this.serializeAnimationRanges();
  25458. // Layer mask
  25459. serializationObject.layerMask = this.layerMask;
  25460. // Alpha
  25461. serializationObject.alphaIndex = this.alphaIndex;
  25462. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  25463. // Overlay
  25464. serializationObject.overlayAlpha = this.overlayAlpha;
  25465. serializationObject.overlayColor = this.overlayColor.asArray();
  25466. serializationObject.renderOverlay = this.renderOverlay;
  25467. // Fog
  25468. serializationObject.applyFog = this.applyFog;
  25469. // Action Manager
  25470. if (this.actionManager) {
  25471. serializationObject.actions = this.actionManager.serialize(this.name);
  25472. }
  25473. };
  25474. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  25475. if (!this.geometry) {
  25476. return;
  25477. }
  25478. this._markSubMeshesAsAttributesDirty();
  25479. var morphTargetManager = this._morphTargetManager;
  25480. if (morphTargetManager && morphTargetManager.vertexCount) {
  25481. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  25482. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  25483. this.morphTargetManager = null;
  25484. return;
  25485. }
  25486. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  25487. var morphTarget = morphTargetManager.getActiveTarget(index);
  25488. var positions = morphTarget.getPositions();
  25489. if (!positions) {
  25490. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  25491. return;
  25492. }
  25493. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  25494. var normals = morphTarget.getNormals();
  25495. if (normals) {
  25496. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  25497. }
  25498. var tangents = morphTarget.getTangents();
  25499. if (tangents) {
  25500. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  25501. }
  25502. }
  25503. }
  25504. else {
  25505. var index = 0;
  25506. // Positions
  25507. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  25508. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  25509. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  25510. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  25511. }
  25512. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  25513. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  25514. }
  25515. index++;
  25516. }
  25517. }
  25518. };
  25519. // Statics
  25520. /**
  25521. * Returns a new Mesh object parsed from the source provided.
  25522. * The parameter `parsedMesh` is the source.
  25523. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  25524. */
  25525. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  25526. var mesh;
  25527. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  25528. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  25529. }
  25530. else {
  25531. mesh = new Mesh(parsedMesh.name, scene);
  25532. }
  25533. mesh.id = parsedMesh.id;
  25534. if (BABYLON.Tags) {
  25535. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  25536. }
  25537. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  25538. if (parsedMesh.metadata !== undefined) {
  25539. mesh.metadata = parsedMesh.metadata;
  25540. }
  25541. if (parsedMesh.rotationQuaternion) {
  25542. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  25543. }
  25544. else if (parsedMesh.rotation) {
  25545. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  25546. }
  25547. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  25548. if (parsedMesh.localMatrix) {
  25549. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  25550. }
  25551. else if (parsedMesh.pivotMatrix) {
  25552. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  25553. }
  25554. mesh.setEnabled(parsedMesh.isEnabled);
  25555. mesh.isVisible = parsedMesh.isVisible;
  25556. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  25557. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  25558. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  25559. if (parsedMesh.applyFog !== undefined) {
  25560. mesh.applyFog = parsedMesh.applyFog;
  25561. }
  25562. if (parsedMesh.pickable !== undefined) {
  25563. mesh.isPickable = parsedMesh.pickable;
  25564. }
  25565. if (parsedMesh.alphaIndex !== undefined) {
  25566. mesh.alphaIndex = parsedMesh.alphaIndex;
  25567. }
  25568. mesh.receiveShadows = parsedMesh.receiveShadows;
  25569. mesh.billboardMode = parsedMesh.billboardMode;
  25570. if (parsedMesh.visibility !== undefined) {
  25571. mesh.visibility = parsedMesh.visibility;
  25572. }
  25573. mesh.checkCollisions = parsedMesh.checkCollisions;
  25574. if (parsedMesh.isBlocker !== undefined) {
  25575. mesh.isBlocker = parsedMesh.isBlocker;
  25576. }
  25577. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  25578. // freezeWorldMatrix
  25579. if (parsedMesh.freezeWorldMatrix) {
  25580. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  25581. }
  25582. // Parent
  25583. if (parsedMesh.parentId) {
  25584. mesh._waitingParentId = parsedMesh.parentId;
  25585. }
  25586. // Actions
  25587. if (parsedMesh.actions !== undefined) {
  25588. mesh._waitingActions = parsedMesh.actions;
  25589. }
  25590. // Overlay
  25591. if (parsedMesh.overlayAlpha !== undefined) {
  25592. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  25593. }
  25594. if (parsedMesh.overlayColor !== undefined) {
  25595. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  25596. }
  25597. if (parsedMesh.renderOverlay !== undefined) {
  25598. mesh.renderOverlay = parsedMesh.renderOverlay;
  25599. }
  25600. // Geometry
  25601. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  25602. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  25603. if (parsedMesh.delayLoadingFile) {
  25604. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  25605. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  25606. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  25607. if (parsedMesh._binaryInfo) {
  25608. mesh._binaryInfo = parsedMesh._binaryInfo;
  25609. }
  25610. mesh._delayInfo = [];
  25611. if (parsedMesh.hasUVs) {
  25612. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  25613. }
  25614. if (parsedMesh.hasUVs2) {
  25615. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  25616. }
  25617. if (parsedMesh.hasUVs3) {
  25618. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  25619. }
  25620. if (parsedMesh.hasUVs4) {
  25621. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  25622. }
  25623. if (parsedMesh.hasUVs5) {
  25624. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  25625. }
  25626. if (parsedMesh.hasUVs6) {
  25627. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  25628. }
  25629. if (parsedMesh.hasColors) {
  25630. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  25631. }
  25632. if (parsedMesh.hasMatricesIndices) {
  25633. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  25634. }
  25635. if (parsedMesh.hasMatricesWeights) {
  25636. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  25637. }
  25638. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  25639. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  25640. mesh._checkDelayState();
  25641. }
  25642. }
  25643. else {
  25644. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  25645. }
  25646. // Material
  25647. if (parsedMesh.materialId) {
  25648. mesh.setMaterialByID(parsedMesh.materialId);
  25649. }
  25650. else {
  25651. mesh.material = null;
  25652. }
  25653. // Morph targets
  25654. if (parsedMesh.morphTargetManagerId > -1) {
  25655. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  25656. }
  25657. // Skeleton
  25658. if (parsedMesh.skeletonId > -1) {
  25659. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  25660. if (parsedMesh.numBoneInfluencers) {
  25661. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  25662. }
  25663. }
  25664. // Animations
  25665. if (parsedMesh.animations) {
  25666. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  25667. var parsedAnimation = parsedMesh.animations[animationIndex];
  25668. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  25669. }
  25670. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  25671. }
  25672. if (parsedMesh.autoAnimate) {
  25673. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  25674. }
  25675. // Layer Mask
  25676. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  25677. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  25678. }
  25679. else {
  25680. mesh.layerMask = 0x0FFFFFFF;
  25681. }
  25682. // Physics
  25683. if (parsedMesh.physicsImpostor) {
  25684. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  25685. mass: parsedMesh.physicsMass,
  25686. friction: parsedMesh.physicsFriction,
  25687. restitution: parsedMesh.physicsRestitution
  25688. }, scene);
  25689. }
  25690. // Instances
  25691. if (parsedMesh.instances) {
  25692. for (var index = 0; index < parsedMesh.instances.length; index++) {
  25693. var parsedInstance = parsedMesh.instances[index];
  25694. var instance = mesh.createInstance(parsedInstance.name);
  25695. if (parsedInstance.id) {
  25696. instance.id = parsedInstance.id;
  25697. }
  25698. if (BABYLON.Tags) {
  25699. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  25700. }
  25701. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  25702. if (parsedInstance.parentId) {
  25703. instance._waitingParentId = parsedInstance.parentId;
  25704. }
  25705. if (parsedInstance.rotationQuaternion) {
  25706. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  25707. }
  25708. else if (parsedInstance.rotation) {
  25709. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  25710. }
  25711. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  25712. instance.checkCollisions = mesh.checkCollisions;
  25713. if (parsedMesh.animations) {
  25714. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  25715. parsedAnimation = parsedMesh.animations[animationIndex];
  25716. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  25717. }
  25718. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  25719. }
  25720. }
  25721. }
  25722. return mesh;
  25723. };
  25724. /**
  25725. * Creates a ribbon mesh.
  25726. * Please consider using the same method from the MeshBuilder class instead.
  25727. * 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.
  25728. *
  25729. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  25730. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  25731. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  25732. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  25733. * 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.
  25734. * 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.
  25735. * 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
  25736. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25737. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25738. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25739. */
  25740. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  25741. if (closeArray === void 0) { closeArray = false; }
  25742. if (updatable === void 0) { updatable = false; }
  25743. return BABYLON.MeshBuilder.CreateRibbon(name, {
  25744. pathArray: pathArray,
  25745. closeArray: closeArray,
  25746. closePath: closePath,
  25747. offset: offset,
  25748. updatable: updatable,
  25749. sideOrientation: sideOrientation,
  25750. instance: instance
  25751. }, scene);
  25752. };
  25753. /**
  25754. * Creates a plane polygonal mesh. By default, this is a disc.
  25755. * Please consider using the same method from the MeshBuilder class instead.
  25756. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  25757. * 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.
  25758. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25759. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25760. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25761. */
  25762. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  25763. if (scene === void 0) { scene = null; }
  25764. var options = {
  25765. radius: radius,
  25766. tessellation: tessellation,
  25767. sideOrientation: sideOrientation,
  25768. updatable: updatable
  25769. };
  25770. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  25771. };
  25772. /**
  25773. * Creates a box mesh.
  25774. * Please consider using the same method from the MeshBuilder class instead.
  25775. * The parameter `size` sets the size (float) of each box side (default 1).
  25776. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25777. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25778. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25779. */
  25780. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  25781. if (scene === void 0) { scene = null; }
  25782. var options = {
  25783. size: size,
  25784. sideOrientation: sideOrientation,
  25785. updatable: updatable
  25786. };
  25787. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  25788. };
  25789. /**
  25790. * Creates a sphere mesh.
  25791. * Please consider using the same method from the MeshBuilder class instead.
  25792. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  25793. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  25794. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25795. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25796. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25797. */
  25798. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  25799. var options = {
  25800. segments: segments,
  25801. diameterX: diameter,
  25802. diameterY: diameter,
  25803. diameterZ: diameter,
  25804. sideOrientation: sideOrientation,
  25805. updatable: updatable
  25806. };
  25807. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  25808. };
  25809. /**
  25810. * Creates a cylinder or a cone mesh.
  25811. * Please consider using the same method from the MeshBuilder class instead.
  25812. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  25813. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  25814. * 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.
  25815. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  25816. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  25817. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25818. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25819. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25820. */
  25821. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  25822. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  25823. if (scene !== undefined) {
  25824. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  25825. updatable = scene;
  25826. }
  25827. scene = subdivisions;
  25828. subdivisions = 1;
  25829. }
  25830. var options = {
  25831. height: height,
  25832. diameterTop: diameterTop,
  25833. diameterBottom: diameterBottom,
  25834. tessellation: tessellation,
  25835. subdivisions: subdivisions,
  25836. sideOrientation: sideOrientation,
  25837. updatable: updatable
  25838. };
  25839. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  25840. };
  25841. // Torus (Code from SharpDX.org)
  25842. /**
  25843. * Creates a torus mesh.
  25844. * Please consider using the same method from the MeshBuilder class instead.
  25845. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  25846. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  25847. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  25848. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25849. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25850. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25851. */
  25852. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  25853. var options = {
  25854. diameter: diameter,
  25855. thickness: thickness,
  25856. tessellation: tessellation,
  25857. sideOrientation: sideOrientation,
  25858. updatable: updatable
  25859. };
  25860. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  25861. };
  25862. /**
  25863. * Creates a torus knot mesh.
  25864. * Please consider using the same method from the MeshBuilder class instead.
  25865. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  25866. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  25867. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  25868. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  25869. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25870. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25871. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25872. */
  25873. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  25874. var options = {
  25875. radius: radius,
  25876. tube: tube,
  25877. radialSegments: radialSegments,
  25878. tubularSegments: tubularSegments,
  25879. p: p,
  25880. q: q,
  25881. sideOrientation: sideOrientation,
  25882. updatable: updatable
  25883. };
  25884. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  25885. };
  25886. /**
  25887. * Creates a line mesh.
  25888. * Please consider using the same method from the MeshBuilder class instead.
  25889. * 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.
  25890. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  25891. * The parameter `points` is an array successive Vector3.
  25892. * 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
  25893. * When updating an instance, remember that only point positions can change, not the number of points.
  25894. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25895. */
  25896. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  25897. if (scene === void 0) { scene = null; }
  25898. if (updatable === void 0) { updatable = false; }
  25899. if (instance === void 0) { instance = null; }
  25900. var options = {
  25901. points: points,
  25902. updatable: updatable,
  25903. instance: instance
  25904. };
  25905. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  25906. };
  25907. /**
  25908. * Creates a dashed line mesh.
  25909. * Please consider using the same method from the MeshBuilder class instead.
  25910. * 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.
  25911. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  25912. * The parameter `points` is an array successive Vector3.
  25913. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  25914. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  25915. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  25916. * 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
  25917. * When updating an instance, remember that only point positions can change, not the number of points.
  25918. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25919. */
  25920. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  25921. if (scene === void 0) { scene = null; }
  25922. var options = {
  25923. points: points,
  25924. dashSize: dashSize,
  25925. gapSize: gapSize,
  25926. dashNb: dashNb,
  25927. updatable: updatable,
  25928. instance: instance
  25929. };
  25930. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  25931. };
  25932. /**
  25933. * Creates a polygon mesh.
  25934. * Please consider using the same method from the MeshBuilder class instead.
  25935. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  25936. * 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.
  25937. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25938. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25939. * Remember you can only change the shape positions, not their number when updating a polygon.
  25940. */
  25941. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  25942. var options = {
  25943. shape: shape,
  25944. holes: holes,
  25945. updatable: updatable,
  25946. sideOrientation: sideOrientation
  25947. };
  25948. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  25949. };
  25950. /**
  25951. * Creates an extruded polygon mesh, with depth in the Y direction.
  25952. * Please consider using the same method from the MeshBuilder class instead.
  25953. */
  25954. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  25955. var options = {
  25956. shape: shape,
  25957. holes: holes,
  25958. depth: depth,
  25959. updatable: updatable,
  25960. sideOrientation: sideOrientation
  25961. };
  25962. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  25963. };
  25964. /**
  25965. * Creates an extruded shape mesh.
  25966. * 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.
  25967. * Please consider using the same method from the MeshBuilder class instead.
  25968. *
  25969. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  25970. * 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
  25971. * extruded along the Z axis.
  25972. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  25973. * 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.
  25974. * The parameter `scale` (float, default 1) is the value to scale the shape.
  25975. * 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
  25976. * 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
  25977. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  25978. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  25979. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  25980. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  25981. */
  25982. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  25983. if (scene === void 0) { scene = null; }
  25984. var options = {
  25985. shape: shape,
  25986. path: path,
  25987. scale: scale,
  25988. rotation: rotation,
  25989. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  25990. sideOrientation: sideOrientation,
  25991. instance: instance,
  25992. updatable: updatable
  25993. };
  25994. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  25995. };
  25996. /**
  25997. * Creates an custom extruded shape mesh.
  25998. * 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.
  25999. * Please consider using the same method from the MeshBuilder class instead.
  26000. *
  26001. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  26002. * 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
  26003. * extruded along the Z axis.
  26004. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  26005. * 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
  26006. * and the distance of this point from the begining of the path :
  26007. * ```javascript
  26008. * var rotationFunction = function(i, distance) {
  26009. * // do things
  26010. * return rotationValue; }
  26011. * ```
  26012. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  26013. * 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
  26014. * and the distance of this point from the begining of the path :
  26015. * ```javascript
  26016. * var scaleFunction = function(i, distance) {
  26017. * // do things
  26018. * return scaleValue;}
  26019. * ```
  26020. * It must returns a float value that will be the scale value applied to the shape on each path point.
  26021. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  26022. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  26023. * 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
  26024. * 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
  26025. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  26026. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26027. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26028. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26029. */
  26030. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  26031. var options = {
  26032. shape: shape,
  26033. path: path,
  26034. scaleFunction: scaleFunction,
  26035. rotationFunction: rotationFunction,
  26036. ribbonCloseArray: ribbonCloseArray,
  26037. ribbonClosePath: ribbonClosePath,
  26038. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  26039. sideOrientation: sideOrientation,
  26040. instance: instance,
  26041. updatable: updatable
  26042. };
  26043. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  26044. };
  26045. /**
  26046. * Creates lathe mesh.
  26047. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  26048. * Please consider using the same method from the MeshBuilder class instead.
  26049. * 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
  26050. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  26051. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  26052. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  26053. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26054. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26055. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26056. */
  26057. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  26058. var options = {
  26059. shape: shape,
  26060. radius: radius,
  26061. tessellation: tessellation,
  26062. sideOrientation: sideOrientation,
  26063. updatable: updatable
  26064. };
  26065. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  26066. };
  26067. /**
  26068. * Creates a plane mesh.
  26069. * Please consider using the same method from the MeshBuilder class instead.
  26070. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  26071. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26072. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26073. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26074. */
  26075. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  26076. var options = {
  26077. size: size,
  26078. width: size,
  26079. height: size,
  26080. sideOrientation: sideOrientation,
  26081. updatable: updatable
  26082. };
  26083. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  26084. };
  26085. /**
  26086. * Creates a ground mesh.
  26087. * Please consider using the same method from the MeshBuilder class instead.
  26088. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  26089. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  26090. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26091. */
  26092. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  26093. var options = {
  26094. width: width,
  26095. height: height,
  26096. subdivisions: subdivisions,
  26097. updatable: updatable
  26098. };
  26099. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  26100. };
  26101. /**
  26102. * Creates a tiled ground mesh.
  26103. * Please consider using the same method from the MeshBuilder class instead.
  26104. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  26105. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  26106. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  26107. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  26108. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  26109. * numbers of subdivisions on the ground width and height of each tile.
  26110. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26111. */
  26112. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  26113. var options = {
  26114. xmin: xmin,
  26115. zmin: zmin,
  26116. xmax: xmax,
  26117. zmax: zmax,
  26118. subdivisions: subdivisions,
  26119. precision: precision,
  26120. updatable: updatable
  26121. };
  26122. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  26123. };
  26124. /**
  26125. * Creates a ground mesh from a height map.
  26126. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  26127. * Please consider using the same method from the MeshBuilder class instead.
  26128. * The parameter `url` sets the URL of the height map image resource.
  26129. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  26130. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  26131. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  26132. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  26133. * 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).
  26134. * This function is passed the newly built mesh :
  26135. * ```javascript
  26136. * function(mesh) { // do things
  26137. * return; }
  26138. * ```
  26139. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26140. */
  26141. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  26142. var options = {
  26143. width: width,
  26144. height: height,
  26145. subdivisions: subdivisions,
  26146. minHeight: minHeight,
  26147. maxHeight: maxHeight,
  26148. updatable: updatable,
  26149. onReady: onReady
  26150. };
  26151. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  26152. };
  26153. /**
  26154. * Creates a tube mesh.
  26155. * 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.
  26156. * Please consider using the same method from the MeshBuilder class instead.
  26157. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  26158. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  26159. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  26160. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  26161. * 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.
  26162. * It must return a radius value (positive float) :
  26163. * ```javascript
  26164. * var radiusFunction = function(i, distance) {
  26165. * // do things
  26166. * return radius; }
  26167. * ```
  26168. * 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
  26169. * 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
  26170. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26171. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26172. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26173. */
  26174. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  26175. var options = {
  26176. path: path,
  26177. radius: radius,
  26178. tessellation: tessellation,
  26179. radiusFunction: radiusFunction,
  26180. arc: 1,
  26181. cap: cap,
  26182. updatable: updatable,
  26183. sideOrientation: sideOrientation,
  26184. instance: instance
  26185. };
  26186. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  26187. };
  26188. /**
  26189. * Creates a polyhedron mesh.
  26190. * Please consider using the same method from the MeshBuilder class instead.
  26191. * 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
  26192. * to choose the wanted type.
  26193. * The parameter `size` (positive float, default 1) sets the polygon size.
  26194. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  26195. * 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`.
  26196. * 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
  26197. * 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)`).
  26198. * 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
  26199. * 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.
  26200. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26201. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26202. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26203. */
  26204. Mesh.CreatePolyhedron = function (name, options, scene) {
  26205. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  26206. };
  26207. /**
  26208. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  26209. * Please consider using the same method from the MeshBuilder class instead.
  26210. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  26211. * 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`).
  26212. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  26213. * 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.
  26214. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  26215. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  26216. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  26217. */
  26218. Mesh.CreateIcoSphere = function (name, options, scene) {
  26219. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  26220. };
  26221. /**
  26222. * Creates a decal mesh.
  26223. * Please consider using the same method from the MeshBuilder class instead.
  26224. * 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.
  26225. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  26226. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  26227. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  26228. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  26229. */
  26230. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  26231. var options = {
  26232. position: position,
  26233. normal: normal,
  26234. size: size,
  26235. angle: angle
  26236. };
  26237. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  26238. };
  26239. // Skeletons
  26240. /**
  26241. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  26242. */
  26243. Mesh.prototype.setPositionsForCPUSkinning = function () {
  26244. if (!this._sourcePositions) {
  26245. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26246. if (!source) {
  26247. return this._sourcePositions;
  26248. }
  26249. this._sourcePositions = new Float32Array(source);
  26250. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  26251. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  26252. }
  26253. }
  26254. return this._sourcePositions;
  26255. };
  26256. /**
  26257. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  26258. */
  26259. Mesh.prototype.setNormalsForCPUSkinning = function () {
  26260. if (!this._sourceNormals) {
  26261. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  26262. if (!source) {
  26263. return this._sourceNormals;
  26264. }
  26265. this._sourceNormals = new Float32Array(source);
  26266. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  26267. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  26268. }
  26269. }
  26270. return this._sourceNormals;
  26271. };
  26272. /**
  26273. * Updates the vertex buffer by applying transformation from the bones.
  26274. * Returns the Mesh.
  26275. *
  26276. * @param {skeleton} skeleton to apply
  26277. */
  26278. Mesh.prototype.applySkeleton = function (skeleton) {
  26279. if (!this.geometry) {
  26280. return this;
  26281. }
  26282. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  26283. return this;
  26284. }
  26285. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  26286. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  26287. return this;
  26288. }
  26289. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  26290. return this;
  26291. }
  26292. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  26293. return this;
  26294. }
  26295. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  26296. return this;
  26297. }
  26298. if (!this._sourcePositions) {
  26299. var submeshes = this.subMeshes.slice();
  26300. this.setPositionsForCPUSkinning();
  26301. this.subMeshes = submeshes;
  26302. }
  26303. if (!this._sourceNormals) {
  26304. this.setNormalsForCPUSkinning();
  26305. }
  26306. // positionsData checks for not being Float32Array will only pass at most once
  26307. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26308. if (!positionsData) {
  26309. return this;
  26310. }
  26311. if (!(positionsData instanceof Float32Array)) {
  26312. positionsData = new Float32Array(positionsData);
  26313. }
  26314. // normalsData checks for not being Float32Array will only pass at most once
  26315. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  26316. if (!normalsData) {
  26317. return this;
  26318. }
  26319. if (!(normalsData instanceof Float32Array)) {
  26320. normalsData = new Float32Array(normalsData);
  26321. }
  26322. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  26323. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  26324. if (!matricesWeightsData || !matricesIndicesData) {
  26325. return this;
  26326. }
  26327. var needExtras = this.numBoneInfluencers > 4;
  26328. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  26329. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  26330. var skeletonMatrices = skeleton.getTransformMatrices(this);
  26331. var tempVector3 = BABYLON.Vector3.Zero();
  26332. var finalMatrix = new BABYLON.Matrix();
  26333. var tempMatrix = new BABYLON.Matrix();
  26334. var matWeightIdx = 0;
  26335. var inf;
  26336. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  26337. var weight;
  26338. for (inf = 0; inf < 4; inf++) {
  26339. weight = matricesWeightsData[matWeightIdx + inf];
  26340. if (weight > 0) {
  26341. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  26342. finalMatrix.addToSelf(tempMatrix);
  26343. }
  26344. else
  26345. break;
  26346. }
  26347. if (needExtras) {
  26348. for (inf = 0; inf < 4; inf++) {
  26349. weight = matricesWeightsExtraData[matWeightIdx + inf];
  26350. if (weight > 0) {
  26351. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  26352. finalMatrix.addToSelf(tempMatrix);
  26353. }
  26354. else
  26355. break;
  26356. }
  26357. }
  26358. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  26359. tempVector3.toArray(positionsData, index);
  26360. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  26361. tempVector3.toArray(normalsData, index);
  26362. finalMatrix.reset();
  26363. }
  26364. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  26365. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  26366. return this;
  26367. };
  26368. // Tools
  26369. /**
  26370. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  26371. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  26372. */
  26373. Mesh.MinMax = function (meshes) {
  26374. var minVector = null;
  26375. var maxVector = null;
  26376. meshes.forEach(function (mesh, index, array) {
  26377. var boundingInfo = mesh.getBoundingInfo();
  26378. var boundingBox = boundingInfo.boundingBox;
  26379. if (!minVector || !maxVector) {
  26380. minVector = boundingBox.minimumWorld;
  26381. maxVector = boundingBox.maximumWorld;
  26382. }
  26383. else {
  26384. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  26385. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  26386. }
  26387. });
  26388. if (!minVector || !maxVector) {
  26389. return {
  26390. min: BABYLON.Vector3.Zero(),
  26391. max: BABYLON.Vector3.Zero()
  26392. };
  26393. }
  26394. return {
  26395. min: minVector,
  26396. max: maxVector
  26397. };
  26398. };
  26399. /**
  26400. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  26401. */
  26402. Mesh.Center = function (meshesOrMinMaxVector) {
  26403. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  26404. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  26405. };
  26406. /**
  26407. * Merge the array of meshes into a single mesh for performance reasons.
  26408. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  26409. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  26410. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  26411. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  26412. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  26413. */
  26414. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  26415. if (disposeSource === void 0) { disposeSource = true; }
  26416. var index;
  26417. if (!allow32BitsIndices) {
  26418. var totalVertices = 0;
  26419. // Counting vertices
  26420. for (index = 0; index < meshes.length; index++) {
  26421. if (meshes[index]) {
  26422. totalVertices += meshes[index].getTotalVertices();
  26423. if (totalVertices > 65536) {
  26424. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  26425. return null;
  26426. }
  26427. }
  26428. }
  26429. }
  26430. // Merge
  26431. var vertexData = null;
  26432. var otherVertexData;
  26433. var indiceArray = new Array();
  26434. var source = null;
  26435. for (index = 0; index < meshes.length; index++) {
  26436. if (meshes[index]) {
  26437. meshes[index].computeWorldMatrix(true);
  26438. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  26439. otherVertexData.transform(meshes[index].getWorldMatrix());
  26440. if (vertexData) {
  26441. vertexData.merge(otherVertexData);
  26442. }
  26443. else {
  26444. vertexData = otherVertexData;
  26445. source = meshes[index];
  26446. }
  26447. if (subdivideWithSubMeshes) {
  26448. indiceArray.push(meshes[index].getTotalIndices());
  26449. }
  26450. }
  26451. }
  26452. source = source;
  26453. if (!meshSubclass) {
  26454. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  26455. }
  26456. vertexData.applyToMesh(meshSubclass);
  26457. // Setting properties
  26458. meshSubclass.material = source.material;
  26459. meshSubclass.checkCollisions = source.checkCollisions;
  26460. // Cleaning
  26461. if (disposeSource) {
  26462. for (index = 0; index < meshes.length; index++) {
  26463. if (meshes[index]) {
  26464. meshes[index].dispose();
  26465. }
  26466. }
  26467. }
  26468. // Subdivide
  26469. if (subdivideWithSubMeshes) {
  26470. //-- Suppresions du submesh global
  26471. meshSubclass.releaseSubMeshes();
  26472. index = 0;
  26473. var offset = 0;
  26474. //-- aplique la subdivision en fonction du tableau d'indices
  26475. while (index < indiceArray.length) {
  26476. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  26477. offset += indiceArray[index];
  26478. index++;
  26479. }
  26480. }
  26481. return meshSubclass;
  26482. };
  26483. // Consts
  26484. Mesh._FRONTSIDE = 0;
  26485. Mesh._BACKSIDE = 1;
  26486. Mesh._DOUBLESIDE = 2;
  26487. Mesh._DEFAULTSIDE = 0;
  26488. Mesh._NO_CAP = 0;
  26489. Mesh._CAP_START = 1;
  26490. Mesh._CAP_END = 2;
  26491. Mesh._CAP_ALL = 3;
  26492. return Mesh;
  26493. }(BABYLON.AbstractMesh));
  26494. BABYLON.Mesh = Mesh;
  26495. })(BABYLON || (BABYLON = {}));
  26496. //# sourceMappingURL=babylon.mesh.js.map
  26497. var BABYLON;
  26498. (function (BABYLON) {
  26499. var BaseSubMesh = /** @class */ (function () {
  26500. function BaseSubMesh() {
  26501. }
  26502. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  26503. get: function () {
  26504. return this._materialEffect;
  26505. },
  26506. enumerable: true,
  26507. configurable: true
  26508. });
  26509. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  26510. if (defines === void 0) { defines = null; }
  26511. if (this._materialEffect === effect) {
  26512. if (!effect) {
  26513. this._materialDefines = null;
  26514. }
  26515. return;
  26516. }
  26517. this._materialDefines = defines;
  26518. this._materialEffect = effect;
  26519. };
  26520. return BaseSubMesh;
  26521. }());
  26522. BABYLON.BaseSubMesh = BaseSubMesh;
  26523. var SubMesh = /** @class */ (function (_super) {
  26524. __extends(SubMesh, _super);
  26525. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  26526. if (createBoundingBox === void 0) { createBoundingBox = true; }
  26527. var _this = _super.call(this) || this;
  26528. _this.materialIndex = materialIndex;
  26529. _this.verticesStart = verticesStart;
  26530. _this.verticesCount = verticesCount;
  26531. _this.indexStart = indexStart;
  26532. _this.indexCount = indexCount;
  26533. _this._renderId = 0;
  26534. _this._mesh = mesh;
  26535. _this._renderingMesh = renderingMesh || mesh;
  26536. mesh.subMeshes.push(_this);
  26537. _this._trianglePlanes = [];
  26538. _this._id = mesh.subMeshes.length - 1;
  26539. if (createBoundingBox) {
  26540. _this.refreshBoundingInfo();
  26541. mesh.computeWorldMatrix(true);
  26542. }
  26543. return _this;
  26544. }
  26545. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  26546. if (createBoundingBox === void 0) { createBoundingBox = true; }
  26547. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  26548. };
  26549. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  26550. get: function () {
  26551. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  26552. },
  26553. enumerable: true,
  26554. configurable: true
  26555. });
  26556. /**
  26557. * Returns the submesh BoudingInfo object.
  26558. */
  26559. SubMesh.prototype.getBoundingInfo = function () {
  26560. if (this.IsGlobal) {
  26561. return this._mesh.getBoundingInfo();
  26562. }
  26563. return this._boundingInfo;
  26564. };
  26565. /**
  26566. * Sets the submesh BoundingInfo.
  26567. * Return the SubMesh.
  26568. */
  26569. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  26570. this._boundingInfo = boundingInfo;
  26571. return this;
  26572. };
  26573. /**
  26574. * Returns the mesh of the current submesh.
  26575. */
  26576. SubMesh.prototype.getMesh = function () {
  26577. return this._mesh;
  26578. };
  26579. /**
  26580. * Returns the rendering mesh of the submesh.
  26581. */
  26582. SubMesh.prototype.getRenderingMesh = function () {
  26583. return this._renderingMesh;
  26584. };
  26585. /**
  26586. * Returns the submesh material.
  26587. */
  26588. SubMesh.prototype.getMaterial = function () {
  26589. var rootMaterial = this._renderingMesh.material;
  26590. if (rootMaterial === null || rootMaterial === undefined) {
  26591. return this._mesh.getScene().defaultMaterial;
  26592. }
  26593. else if (rootMaterial.getSubMaterial) {
  26594. var multiMaterial = rootMaterial;
  26595. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  26596. if (this._currentMaterial !== effectiveMaterial) {
  26597. this._currentMaterial = effectiveMaterial;
  26598. this._materialDefines = null;
  26599. }
  26600. return effectiveMaterial;
  26601. }
  26602. return rootMaterial;
  26603. };
  26604. // Methods
  26605. /**
  26606. * Sets a new updated BoundingInfo object to the submesh.
  26607. * Returns the SubMesh.
  26608. */
  26609. SubMesh.prototype.refreshBoundingInfo = function () {
  26610. this._lastColliderWorldVertices = null;
  26611. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  26612. return this;
  26613. }
  26614. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26615. if (!data) {
  26616. this._boundingInfo = this._mesh.getBoundingInfo();
  26617. return this;
  26618. }
  26619. var indices = this._renderingMesh.getIndices();
  26620. var extend;
  26621. //is this the only submesh?
  26622. if (this.indexStart === 0 && this.indexCount === indices.length) {
  26623. var boundingInfo = this._renderingMesh.getBoundingInfo();
  26624. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  26625. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  26626. }
  26627. else {
  26628. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  26629. }
  26630. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  26631. return this;
  26632. };
  26633. SubMesh.prototype._checkCollision = function (collider) {
  26634. var boundingInfo = this._renderingMesh.getBoundingInfo();
  26635. return boundingInfo._checkCollision(collider);
  26636. };
  26637. /**
  26638. * Updates the submesh BoundingInfo.
  26639. * Returns the Submesh.
  26640. */
  26641. SubMesh.prototype.updateBoundingInfo = function (world) {
  26642. var boundingInfo = this.getBoundingInfo();
  26643. if (!boundingInfo) {
  26644. this.refreshBoundingInfo();
  26645. boundingInfo = this.getBoundingInfo();
  26646. }
  26647. boundingInfo.update(world);
  26648. return this;
  26649. };
  26650. /**
  26651. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  26652. * Boolean returned.
  26653. */
  26654. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  26655. var boundingInfo = this.getBoundingInfo();
  26656. if (!boundingInfo) {
  26657. return false;
  26658. }
  26659. return boundingInfo.isInFrustum(frustumPlanes);
  26660. };
  26661. /**
  26662. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  26663. * Boolean returned.
  26664. */
  26665. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  26666. var boundingInfo = this.getBoundingInfo();
  26667. if (!boundingInfo) {
  26668. return false;
  26669. }
  26670. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  26671. };
  26672. /**
  26673. * Renders the submesh.
  26674. * Returns it.
  26675. */
  26676. SubMesh.prototype.render = function (enableAlphaMode) {
  26677. this._renderingMesh.render(this, enableAlphaMode);
  26678. return this;
  26679. };
  26680. /**
  26681. * Returns a new Index Buffer.
  26682. * Type returned : WebGLBuffer.
  26683. */
  26684. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  26685. if (!this._linesIndexBuffer) {
  26686. var linesIndices = [];
  26687. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  26688. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  26689. }
  26690. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  26691. this.linesIndexCount = linesIndices.length;
  26692. }
  26693. return this._linesIndexBuffer;
  26694. };
  26695. /**
  26696. * True is the passed Ray intersects the submesh bounding box.
  26697. * Boolean returned.
  26698. */
  26699. SubMesh.prototype.canIntersects = function (ray) {
  26700. var boundingInfo = this.getBoundingInfo();
  26701. if (!boundingInfo) {
  26702. return false;
  26703. }
  26704. return ray.intersectsBox(boundingInfo.boundingBox);
  26705. };
  26706. /**
  26707. * Returns an object IntersectionInfo.
  26708. */
  26709. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  26710. var intersectInfo = null;
  26711. // LineMesh first as it's also a Mesh...
  26712. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  26713. var lineMesh = this._mesh;
  26714. // Line test
  26715. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  26716. var p0 = positions[indices[index]];
  26717. var p1 = positions[indices[index + 1]];
  26718. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  26719. if (length < 0) {
  26720. continue;
  26721. }
  26722. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  26723. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  26724. if (fastCheck) {
  26725. break;
  26726. }
  26727. }
  26728. }
  26729. }
  26730. else {
  26731. // Triangles test
  26732. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  26733. var p0 = positions[indices[index]];
  26734. var p1 = positions[indices[index + 1]];
  26735. var p2 = positions[indices[index + 2]];
  26736. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  26737. if (currentIntersectInfo) {
  26738. if (currentIntersectInfo.distance < 0) {
  26739. continue;
  26740. }
  26741. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  26742. intersectInfo = currentIntersectInfo;
  26743. intersectInfo.faceId = index / 3;
  26744. if (fastCheck) {
  26745. break;
  26746. }
  26747. }
  26748. }
  26749. }
  26750. }
  26751. return intersectInfo;
  26752. };
  26753. SubMesh.prototype._rebuild = function () {
  26754. if (this._linesIndexBuffer) {
  26755. this._linesIndexBuffer = null;
  26756. }
  26757. };
  26758. // Clone
  26759. /**
  26760. * Creates a new Submesh from the passed Mesh.
  26761. */
  26762. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  26763. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  26764. if (!this.IsGlobal) {
  26765. var boundingInfo = this.getBoundingInfo();
  26766. if (!boundingInfo) {
  26767. return result;
  26768. }
  26769. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  26770. }
  26771. return result;
  26772. };
  26773. // Dispose
  26774. /**
  26775. * Disposes the Submesh.
  26776. * Returns nothing.
  26777. */
  26778. SubMesh.prototype.dispose = function () {
  26779. if (this._linesIndexBuffer) {
  26780. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  26781. this._linesIndexBuffer = null;
  26782. }
  26783. // Remove from mesh
  26784. var index = this._mesh.subMeshes.indexOf(this);
  26785. this._mesh.subMeshes.splice(index, 1);
  26786. };
  26787. // Statics
  26788. /**
  26789. * Creates a new Submesh from the passed parameters :
  26790. * - materialIndex (integer) : the index of the main mesh material.
  26791. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  26792. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  26793. * - mesh (Mesh) : the main mesh to create the submesh from.
  26794. * - renderingMesh (optional Mesh) : rendering mesh.
  26795. */
  26796. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  26797. var minVertexIndex = Number.MAX_VALUE;
  26798. var maxVertexIndex = -Number.MAX_VALUE;
  26799. renderingMesh = (renderingMesh || mesh);
  26800. var indices = renderingMesh.getIndices();
  26801. for (var index = startIndex; index < startIndex + indexCount; index++) {
  26802. var vertexIndex = indices[index];
  26803. if (vertexIndex < minVertexIndex)
  26804. minVertexIndex = vertexIndex;
  26805. if (vertexIndex > maxVertexIndex)
  26806. maxVertexIndex = vertexIndex;
  26807. }
  26808. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  26809. };
  26810. return SubMesh;
  26811. }(BaseSubMesh));
  26812. BABYLON.SubMesh = SubMesh;
  26813. })(BABYLON || (BABYLON = {}));
  26814. //# sourceMappingURL=babylon.subMesh.js.map
  26815. var BABYLON;
  26816. (function (BABYLON) {
  26817. var EffectFallbacks = /** @class */ (function () {
  26818. function EffectFallbacks() {
  26819. this._defines = {};
  26820. this._currentRank = 32;
  26821. this._maxRank = -1;
  26822. }
  26823. EffectFallbacks.prototype.unBindMesh = function () {
  26824. this._mesh = null;
  26825. };
  26826. EffectFallbacks.prototype.addFallback = function (rank, define) {
  26827. if (!this._defines[rank]) {
  26828. if (rank < this._currentRank) {
  26829. this._currentRank = rank;
  26830. }
  26831. if (rank > this._maxRank) {
  26832. this._maxRank = rank;
  26833. }
  26834. this._defines[rank] = new Array();
  26835. }
  26836. this._defines[rank].push(define);
  26837. };
  26838. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  26839. this._mesh = mesh;
  26840. if (rank < this._currentRank) {
  26841. this._currentRank = rank;
  26842. }
  26843. if (rank > this._maxRank) {
  26844. this._maxRank = rank;
  26845. }
  26846. };
  26847. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  26848. get: function () {
  26849. return this._currentRank <= this._maxRank;
  26850. },
  26851. enumerable: true,
  26852. configurable: true
  26853. });
  26854. EffectFallbacks.prototype.reduce = function (currentDefines) {
  26855. // First we try to switch to CPU skinning
  26856. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0) {
  26857. this._mesh.computeBonesUsingShaders = false;
  26858. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  26859. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  26860. var scene = this._mesh.getScene();
  26861. for (var index = 0; index < scene.meshes.length; index++) {
  26862. var otherMesh = scene.meshes[index];
  26863. if (otherMesh.material === this._mesh.material && otherMesh.computeBonesUsingShaders && otherMesh.numBoneInfluencers > 0) {
  26864. otherMesh.computeBonesUsingShaders = false;
  26865. }
  26866. }
  26867. }
  26868. else {
  26869. var currentFallbacks = this._defines[this._currentRank];
  26870. if (currentFallbacks) {
  26871. for (var index = 0; index < currentFallbacks.length; index++) {
  26872. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  26873. }
  26874. }
  26875. this._currentRank++;
  26876. }
  26877. return currentDefines;
  26878. };
  26879. return EffectFallbacks;
  26880. }());
  26881. BABYLON.EffectFallbacks = EffectFallbacks;
  26882. var EffectCreationOptions = /** @class */ (function () {
  26883. function EffectCreationOptions() {
  26884. }
  26885. return EffectCreationOptions;
  26886. }());
  26887. BABYLON.EffectCreationOptions = EffectCreationOptions;
  26888. var Effect = /** @class */ (function () {
  26889. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  26890. if (samplers === void 0) { samplers = null; }
  26891. if (defines === void 0) { defines = null; }
  26892. if (fallbacks === void 0) { fallbacks = null; }
  26893. if (onCompiled === void 0) { onCompiled = null; }
  26894. if (onError === void 0) { onError = null; }
  26895. var _this = this;
  26896. this.uniqueId = 0;
  26897. this.onCompileObservable = new BABYLON.Observable();
  26898. this.onErrorObservable = new BABYLON.Observable();
  26899. this.onBindObservable = new BABYLON.Observable();
  26900. this._uniformBuffersNames = {};
  26901. this._isReady = false;
  26902. this._compilationError = "";
  26903. this.name = baseName;
  26904. if (attributesNamesOrOptions.attributes) {
  26905. var options = attributesNamesOrOptions;
  26906. this._engine = uniformsNamesOrEngine;
  26907. this._attributesNames = options.attributes;
  26908. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  26909. this._samplers = options.samplers;
  26910. this.defines = options.defines;
  26911. this.onError = options.onError;
  26912. this.onCompiled = options.onCompiled;
  26913. this._fallbacks = options.fallbacks;
  26914. this._indexParameters = options.indexParameters;
  26915. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  26916. if (options.uniformBuffersNames) {
  26917. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  26918. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  26919. }
  26920. }
  26921. }
  26922. else {
  26923. this._engine = engine;
  26924. this.defines = defines;
  26925. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  26926. this._samplers = samplers;
  26927. this._attributesNames = attributesNamesOrOptions;
  26928. this.onError = onError;
  26929. this.onCompiled = onCompiled;
  26930. this._indexParameters = indexParameters;
  26931. this._fallbacks = fallbacks;
  26932. }
  26933. this.uniqueId = Effect._uniqueIdSeed++;
  26934. var vertexSource;
  26935. var fragmentSource;
  26936. if (baseName.vertexElement) {
  26937. vertexSource = document.getElementById(baseName.vertexElement);
  26938. if (!vertexSource) {
  26939. vertexSource = baseName.vertexElement;
  26940. }
  26941. }
  26942. else {
  26943. vertexSource = baseName.vertex || baseName;
  26944. }
  26945. if (baseName.fragmentElement) {
  26946. fragmentSource = document.getElementById(baseName.fragmentElement);
  26947. if (!fragmentSource) {
  26948. fragmentSource = baseName.fragmentElement;
  26949. }
  26950. }
  26951. else {
  26952. fragmentSource = baseName.fragment || baseName;
  26953. }
  26954. this._loadVertexShader(vertexSource, function (vertexCode) {
  26955. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  26956. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  26957. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  26958. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  26959. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  26960. if (baseName) {
  26961. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  26962. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  26963. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  26964. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  26965. }
  26966. else {
  26967. _this._vertexSourceCode = migratedVertexCode;
  26968. _this._fragmentSourceCode = migratedFragmentCode;
  26969. }
  26970. _this._prepareEffect();
  26971. });
  26972. });
  26973. });
  26974. });
  26975. });
  26976. });
  26977. }
  26978. Object.defineProperty(Effect.prototype, "key", {
  26979. get: function () {
  26980. return this._key;
  26981. },
  26982. enumerable: true,
  26983. configurable: true
  26984. });
  26985. // Properties
  26986. Effect.prototype.isReady = function () {
  26987. return this._isReady;
  26988. };
  26989. Effect.prototype.getEngine = function () {
  26990. return this._engine;
  26991. };
  26992. Effect.prototype.getProgram = function () {
  26993. return this._program;
  26994. };
  26995. Effect.prototype.getAttributesNames = function () {
  26996. return this._attributesNames;
  26997. };
  26998. Effect.prototype.getAttributeLocation = function (index) {
  26999. return this._attributes[index];
  27000. };
  27001. Effect.prototype.getAttributeLocationByName = function (name) {
  27002. var index = this._attributesNames.indexOf(name);
  27003. return this._attributes[index];
  27004. };
  27005. Effect.prototype.getAttributesCount = function () {
  27006. return this._attributes.length;
  27007. };
  27008. Effect.prototype.getUniformIndex = function (uniformName) {
  27009. return this._uniformsNames.indexOf(uniformName);
  27010. };
  27011. Effect.prototype.getUniform = function (uniformName) {
  27012. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  27013. };
  27014. Effect.prototype.getSamplers = function () {
  27015. return this._samplers;
  27016. };
  27017. Effect.prototype.getCompilationError = function () {
  27018. return this._compilationError;
  27019. };
  27020. // Methods
  27021. Effect.prototype.executeWhenCompiled = function (func) {
  27022. if (this.isReady()) {
  27023. func(this);
  27024. return;
  27025. }
  27026. this.onCompileObservable.add(function (effect) {
  27027. func(effect);
  27028. });
  27029. };
  27030. Effect.prototype._loadVertexShader = function (vertex, callback) {
  27031. if (BABYLON.Tools.IsWindowObjectExist()) {
  27032. // DOM element ?
  27033. if (vertex instanceof HTMLElement) {
  27034. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  27035. callback(vertexCode);
  27036. return;
  27037. }
  27038. }
  27039. // Base64 encoded ?
  27040. if (vertex.substr(0, 7) === "base64:") {
  27041. var vertexBinary = window.atob(vertex.substr(7));
  27042. callback(vertexBinary);
  27043. return;
  27044. }
  27045. // Is in local store ?
  27046. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  27047. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  27048. return;
  27049. }
  27050. var vertexShaderUrl;
  27051. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  27052. vertexShaderUrl = vertex;
  27053. }
  27054. else {
  27055. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  27056. }
  27057. // Vertex shader
  27058. this._engine._loadFile(vertexShaderUrl + ".vertex.fx", callback);
  27059. };
  27060. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  27061. if (BABYLON.Tools.IsWindowObjectExist()) {
  27062. // DOM element ?
  27063. if (fragment instanceof HTMLElement) {
  27064. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  27065. callback(fragmentCode);
  27066. return;
  27067. }
  27068. }
  27069. // Base64 encoded ?
  27070. if (fragment.substr(0, 7) === "base64:") {
  27071. var fragmentBinary = window.atob(fragment.substr(7));
  27072. callback(fragmentBinary);
  27073. return;
  27074. }
  27075. // Is in local store ?
  27076. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  27077. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  27078. return;
  27079. }
  27080. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  27081. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  27082. return;
  27083. }
  27084. var fragmentShaderUrl;
  27085. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  27086. fragmentShaderUrl = fragment;
  27087. }
  27088. else {
  27089. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  27090. }
  27091. // Fragment shader
  27092. this._engine._loadFile(fragmentShaderUrl + ".fragment.fx", callback);
  27093. };
  27094. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  27095. // Rebuild shaders source code
  27096. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n" : "";
  27097. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  27098. vertexCode = prefix + vertexCode;
  27099. fragmentCode = prefix + fragmentCode;
  27100. // Number lines of shaders source code
  27101. var i = 2;
  27102. var regex = /\n/gm;
  27103. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  27104. i = 2;
  27105. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  27106. // Dump shaders name and formatted source code
  27107. if (this.name.vertexElement) {
  27108. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  27109. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  27110. }
  27111. else if (this.name.vertex) {
  27112. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  27113. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  27114. }
  27115. else {
  27116. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  27117. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  27118. }
  27119. };
  27120. ;
  27121. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  27122. var preparedSourceCode = this._processPrecision(sourceCode);
  27123. if (this._engine.webGLVersion == 1) {
  27124. callback(preparedSourceCode);
  27125. return;
  27126. }
  27127. // Already converted
  27128. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  27129. callback(preparedSourceCode.replace("#version 300 es", ""));
  27130. return;
  27131. }
  27132. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  27133. // Remove extensions
  27134. // #extension GL_OES_standard_derivatives : enable
  27135. // #extension GL_EXT_shader_texture_lod : enable
  27136. // #extension GL_EXT_frag_depth : enable
  27137. // #extension GL_EXT_draw_buffers : require
  27138. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  27139. var result = preparedSourceCode.replace(regex, "");
  27140. // Migrate to GLSL v300
  27141. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  27142. result = result.replace(/attribute[ \t]/g, "in ");
  27143. result = result.replace(/[ \t]attribute/g, " in");
  27144. if (isFragment) {
  27145. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  27146. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  27147. result = result.replace(/texture2D\s*\(/g, "texture(");
  27148. result = result.replace(/textureCube\s*\(/g, "texture(");
  27149. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  27150. result = result.replace(/gl_FragColor/g, "glFragColor");
  27151. result = result.replace(/gl_FragData/g, "glFragData");
  27152. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  27153. }
  27154. callback(result);
  27155. };
  27156. Effect.prototype._processIncludes = function (sourceCode, callback) {
  27157. var _this = this;
  27158. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  27159. var match = regex.exec(sourceCode);
  27160. var returnValue = new String(sourceCode);
  27161. while (match != null) {
  27162. var includeFile = match[1];
  27163. // Uniform declaration
  27164. if (includeFile.indexOf("__decl__") !== -1) {
  27165. includeFile = includeFile.replace(/__decl__/, "");
  27166. if (this._engine.supportsUniformBuffers) {
  27167. includeFile = includeFile.replace(/Vertex/, "Ubo");
  27168. includeFile = includeFile.replace(/Fragment/, "Ubo");
  27169. }
  27170. includeFile = includeFile + "Declaration";
  27171. }
  27172. if (Effect.IncludesShadersStore[includeFile]) {
  27173. // Substitution
  27174. var includeContent = Effect.IncludesShadersStore[includeFile];
  27175. if (match[2]) {
  27176. var splits = match[3].split(",");
  27177. for (var index = 0; index < splits.length; index += 2) {
  27178. var source = new RegExp(splits[index], "g");
  27179. var dest = splits[index + 1];
  27180. includeContent = includeContent.replace(source, dest);
  27181. }
  27182. }
  27183. if (match[4]) {
  27184. var indexString = match[5];
  27185. if (indexString.indexOf("..") !== -1) {
  27186. var indexSplits = indexString.split("..");
  27187. var minIndex = parseInt(indexSplits[0]);
  27188. var maxIndex = parseInt(indexSplits[1]);
  27189. var sourceIncludeContent = includeContent.slice(0);
  27190. includeContent = "";
  27191. if (isNaN(maxIndex)) {
  27192. maxIndex = this._indexParameters[indexSplits[1]];
  27193. }
  27194. for (var i = minIndex; i < maxIndex; i++) {
  27195. if (!this._engine.supportsUniformBuffers) {
  27196. // Ubo replacement
  27197. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  27198. return p1 + "{X}";
  27199. });
  27200. }
  27201. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  27202. }
  27203. }
  27204. else {
  27205. if (!this._engine.supportsUniformBuffers) {
  27206. // Ubo replacement
  27207. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  27208. return p1 + "{X}";
  27209. });
  27210. }
  27211. includeContent = includeContent.replace(/\{X\}/g, indexString);
  27212. }
  27213. }
  27214. // Replace
  27215. returnValue = returnValue.replace(match[0], includeContent);
  27216. }
  27217. else {
  27218. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  27219. this._engine._loadFile(includeShaderUrl, function (fileContent) {
  27220. Effect.IncludesShadersStore[includeFile] = fileContent;
  27221. _this._processIncludes(returnValue, callback);
  27222. });
  27223. return;
  27224. }
  27225. match = regex.exec(sourceCode);
  27226. }
  27227. callback(returnValue);
  27228. };
  27229. Effect.prototype._processPrecision = function (source) {
  27230. if (source.indexOf("precision highp float") === -1) {
  27231. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  27232. source = "precision mediump float;\n" + source;
  27233. }
  27234. else {
  27235. source = "precision highp float;\n" + source;
  27236. }
  27237. }
  27238. else {
  27239. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  27240. source = source.replace("precision highp float", "precision mediump float");
  27241. }
  27242. }
  27243. return source;
  27244. };
  27245. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  27246. var _this = this;
  27247. this._isReady = false;
  27248. this._vertexSourceCodeOverride = vertexSourceCode;
  27249. this._fragmentSourceCodeOverride = fragmentSourceCode;
  27250. this.onError = function (effect, error) {
  27251. if (onError) {
  27252. onError(error);
  27253. }
  27254. };
  27255. this.onCompiled = function () {
  27256. var scenes = _this.getEngine().scenes;
  27257. for (var i = 0; i < scenes.length; i++) {
  27258. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  27259. }
  27260. if (onCompiled) {
  27261. onCompiled(_this._program);
  27262. }
  27263. };
  27264. this._fallbacks = null;
  27265. this._prepareEffect();
  27266. };
  27267. Effect.prototype.getSpecificUniformLocations = function (names) {
  27268. var engine = this._engine;
  27269. return engine.getUniforms(this._program, names);
  27270. };
  27271. Effect.prototype._prepareEffect = function () {
  27272. var attributesNames = this._attributesNames;
  27273. var defines = this.defines;
  27274. var fallbacks = this._fallbacks;
  27275. this._valueCache = {};
  27276. var previousProgram = this._program;
  27277. try {
  27278. var engine = this._engine;
  27279. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  27280. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  27281. }
  27282. else {
  27283. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  27284. }
  27285. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  27286. if (engine.supportsUniformBuffers) {
  27287. for (var name in this._uniformBuffersNames) {
  27288. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  27289. }
  27290. }
  27291. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  27292. this._attributes = engine.getAttributes(this._program, attributesNames);
  27293. var index;
  27294. for (index = 0; index < this._samplers.length; index++) {
  27295. var sampler = this.getUniform(this._samplers[index]);
  27296. if (sampler == null) {
  27297. this._samplers.splice(index, 1);
  27298. index--;
  27299. }
  27300. }
  27301. engine.bindSamplers(this);
  27302. this._compilationError = "";
  27303. this._isReady = true;
  27304. if (this.onCompiled) {
  27305. this.onCompiled(this);
  27306. }
  27307. this.onCompileObservable.notifyObservers(this);
  27308. this.onCompileObservable.clear();
  27309. // Unbind mesh reference in fallbacks
  27310. if (this._fallbacks) {
  27311. this._fallbacks.unBindMesh();
  27312. }
  27313. if (previousProgram) {
  27314. this.getEngine()._deleteProgram(previousProgram);
  27315. }
  27316. }
  27317. catch (e) {
  27318. this._compilationError = e.message;
  27319. // Let's go through fallbacks then
  27320. BABYLON.Tools.Error("Unable to compile effect:");
  27321. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  27322. return " " + uniform;
  27323. }));
  27324. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  27325. return " " + attribute;
  27326. }));
  27327. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  27328. BABYLON.Tools.Error("Error: " + this._compilationError);
  27329. if (previousProgram) {
  27330. this._program = previousProgram;
  27331. this._isReady = true;
  27332. if (this.onError) {
  27333. this.onError(this, this._compilationError);
  27334. }
  27335. this.onErrorObservable.notifyObservers(this);
  27336. }
  27337. if (fallbacks && fallbacks.isMoreFallbacks) {
  27338. BABYLON.Tools.Error("Trying next fallback.");
  27339. this.defines = fallbacks.reduce(this.defines);
  27340. this._prepareEffect();
  27341. }
  27342. else {
  27343. if (this.onError) {
  27344. this.onError(this, this._compilationError);
  27345. }
  27346. this.onErrorObservable.notifyObservers(this);
  27347. this.onErrorObservable.clear();
  27348. // Unbind mesh reference in fallbacks
  27349. if (this._fallbacks) {
  27350. this._fallbacks.unBindMesh();
  27351. }
  27352. }
  27353. }
  27354. };
  27355. Object.defineProperty(Effect.prototype, "isSupported", {
  27356. get: function () {
  27357. return this._compilationError === "";
  27358. },
  27359. enumerable: true,
  27360. configurable: true
  27361. });
  27362. Effect.prototype._bindTexture = function (channel, texture) {
  27363. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  27364. };
  27365. Effect.prototype.setTexture = function (channel, texture) {
  27366. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  27367. };
  27368. Effect.prototype.setTextureArray = function (channel, textures) {
  27369. if (this._samplers.indexOf(channel + "Ex") === -1) {
  27370. var initialPos = this._samplers.indexOf(channel);
  27371. for (var index = 1; index < textures.length; index++) {
  27372. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  27373. }
  27374. }
  27375. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  27376. };
  27377. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  27378. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  27379. };
  27380. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  27381. var cache = this._valueCache[uniformName];
  27382. var flag = matrix.updateFlag;
  27383. if (cache !== undefined && cache === flag) {
  27384. return false;
  27385. }
  27386. this._valueCache[uniformName] = flag;
  27387. return true;
  27388. };
  27389. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  27390. var cache = this._valueCache[uniformName];
  27391. if (!cache) {
  27392. cache = [x, y];
  27393. this._valueCache[uniformName] = cache;
  27394. return true;
  27395. }
  27396. var changed = false;
  27397. if (cache[0] !== x) {
  27398. cache[0] = x;
  27399. changed = true;
  27400. }
  27401. if (cache[1] !== y) {
  27402. cache[1] = y;
  27403. changed = true;
  27404. }
  27405. return changed;
  27406. };
  27407. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  27408. var cache = this._valueCache[uniformName];
  27409. if (!cache) {
  27410. cache = [x, y, z];
  27411. this._valueCache[uniformName] = cache;
  27412. return true;
  27413. }
  27414. var changed = false;
  27415. if (cache[0] !== x) {
  27416. cache[0] = x;
  27417. changed = true;
  27418. }
  27419. if (cache[1] !== y) {
  27420. cache[1] = y;
  27421. changed = true;
  27422. }
  27423. if (cache[2] !== z) {
  27424. cache[2] = z;
  27425. changed = true;
  27426. }
  27427. return changed;
  27428. };
  27429. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  27430. var cache = this._valueCache[uniformName];
  27431. if (!cache) {
  27432. cache = [x, y, z, w];
  27433. this._valueCache[uniformName] = cache;
  27434. return true;
  27435. }
  27436. var changed = false;
  27437. if (cache[0] !== x) {
  27438. cache[0] = x;
  27439. changed = true;
  27440. }
  27441. if (cache[1] !== y) {
  27442. cache[1] = y;
  27443. changed = true;
  27444. }
  27445. if (cache[2] !== z) {
  27446. cache[2] = z;
  27447. changed = true;
  27448. }
  27449. if (cache[3] !== w) {
  27450. cache[3] = w;
  27451. changed = true;
  27452. }
  27453. return changed;
  27454. };
  27455. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  27456. var bufferName = this._uniformBuffersNames[name];
  27457. if (Effect._baseCache[bufferName] === buffer) {
  27458. return;
  27459. }
  27460. Effect._baseCache[bufferName] = buffer;
  27461. this._engine.bindUniformBufferBase(buffer, bufferName);
  27462. };
  27463. Effect.prototype.bindUniformBlock = function (blockName, index) {
  27464. this._engine.bindUniformBlock(this._program, blockName, index);
  27465. };
  27466. Effect.prototype.setInt = function (uniformName, value) {
  27467. var cache = this._valueCache[uniformName];
  27468. if (cache !== undefined && cache === value)
  27469. return this;
  27470. this._valueCache[uniformName] = value;
  27471. this._engine.setInt(this.getUniform(uniformName), value);
  27472. return this;
  27473. };
  27474. Effect.prototype.setIntArray = function (uniformName, array) {
  27475. this._valueCache[uniformName] = null;
  27476. this._engine.setIntArray(this.getUniform(uniformName), array);
  27477. return this;
  27478. };
  27479. Effect.prototype.setIntArray2 = function (uniformName, array) {
  27480. this._valueCache[uniformName] = null;
  27481. this._engine.setIntArray2(this.getUniform(uniformName), array);
  27482. return this;
  27483. };
  27484. Effect.prototype.setIntArray3 = function (uniformName, array) {
  27485. this._valueCache[uniformName] = null;
  27486. this._engine.setIntArray3(this.getUniform(uniformName), array);
  27487. return this;
  27488. };
  27489. Effect.prototype.setIntArray4 = function (uniformName, array) {
  27490. this._valueCache[uniformName] = null;
  27491. this._engine.setIntArray4(this.getUniform(uniformName), array);
  27492. return this;
  27493. };
  27494. Effect.prototype.setFloatArray = function (uniformName, array) {
  27495. this._valueCache[uniformName] = null;
  27496. this._engine.setFloatArray(this.getUniform(uniformName), array);
  27497. return this;
  27498. };
  27499. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  27500. this._valueCache[uniformName] = null;
  27501. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  27502. return this;
  27503. };
  27504. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  27505. this._valueCache[uniformName] = null;
  27506. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  27507. return this;
  27508. };
  27509. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  27510. this._valueCache[uniformName] = null;
  27511. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  27512. return this;
  27513. };
  27514. Effect.prototype.setArray = function (uniformName, array) {
  27515. this._valueCache[uniformName] = null;
  27516. this._engine.setArray(this.getUniform(uniformName), array);
  27517. return this;
  27518. };
  27519. Effect.prototype.setArray2 = function (uniformName, array) {
  27520. this._valueCache[uniformName] = null;
  27521. this._engine.setArray2(this.getUniform(uniformName), array);
  27522. return this;
  27523. };
  27524. Effect.prototype.setArray3 = function (uniformName, array) {
  27525. this._valueCache[uniformName] = null;
  27526. this._engine.setArray3(this.getUniform(uniformName), array);
  27527. return this;
  27528. };
  27529. Effect.prototype.setArray4 = function (uniformName, array) {
  27530. this._valueCache[uniformName] = null;
  27531. this._engine.setArray4(this.getUniform(uniformName), array);
  27532. return this;
  27533. };
  27534. Effect.prototype.setMatrices = function (uniformName, matrices) {
  27535. if (!matrices) {
  27536. return this;
  27537. }
  27538. this._valueCache[uniformName] = null;
  27539. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  27540. return this;
  27541. };
  27542. Effect.prototype.setMatrix = function (uniformName, matrix) {
  27543. if (this._cacheMatrix(uniformName, matrix)) {
  27544. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  27545. }
  27546. return this;
  27547. };
  27548. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  27549. this._valueCache[uniformName] = null;
  27550. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  27551. return this;
  27552. };
  27553. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  27554. this._valueCache[uniformName] = null;
  27555. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  27556. return this;
  27557. };
  27558. Effect.prototype.setFloat = function (uniformName, value) {
  27559. var cache = this._valueCache[uniformName];
  27560. if (cache !== undefined && cache === value)
  27561. return this;
  27562. this._valueCache[uniformName] = value;
  27563. this._engine.setFloat(this.getUniform(uniformName), value);
  27564. return this;
  27565. };
  27566. Effect.prototype.setBool = function (uniformName, bool) {
  27567. var cache = this._valueCache[uniformName];
  27568. if (cache !== undefined && cache === bool)
  27569. return this;
  27570. this._valueCache[uniformName] = bool;
  27571. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  27572. return this;
  27573. };
  27574. Effect.prototype.setVector2 = function (uniformName, vector2) {
  27575. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  27576. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  27577. }
  27578. return this;
  27579. };
  27580. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  27581. if (this._cacheFloat2(uniformName, x, y)) {
  27582. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  27583. }
  27584. return this;
  27585. };
  27586. Effect.prototype.setVector3 = function (uniformName, vector3) {
  27587. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  27588. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  27589. }
  27590. return this;
  27591. };
  27592. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  27593. if (this._cacheFloat3(uniformName, x, y, z)) {
  27594. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  27595. }
  27596. return this;
  27597. };
  27598. Effect.prototype.setVector4 = function (uniformName, vector4) {
  27599. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  27600. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  27601. }
  27602. return this;
  27603. };
  27604. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  27605. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  27606. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  27607. }
  27608. return this;
  27609. };
  27610. Effect.prototype.setColor3 = function (uniformName, color3) {
  27611. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  27612. this._engine.setColor3(this.getUniform(uniformName), color3);
  27613. }
  27614. return this;
  27615. };
  27616. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  27617. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  27618. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  27619. }
  27620. return this;
  27621. };
  27622. Effect.ResetCache = function () {
  27623. Effect._baseCache = {};
  27624. };
  27625. Effect._uniqueIdSeed = 0;
  27626. Effect._baseCache = {};
  27627. // Statics
  27628. Effect.ShadersStore = {};
  27629. Effect.IncludesShadersStore = {};
  27630. return Effect;
  27631. }());
  27632. BABYLON.Effect = Effect;
  27633. })(BABYLON || (BABYLON = {}));
  27634. //# sourceMappingURL=babylon.effect.js.map
  27635. var __assign = (this && this.__assign) || Object.assign || function(t) {
  27636. for (var s, i = 1, n = arguments.length; i < n; i++) {
  27637. s = arguments[i];
  27638. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  27639. t[p] = s[p];
  27640. }
  27641. return t;
  27642. };
  27643. var BABYLON;
  27644. (function (BABYLON) {
  27645. var MaterialDefines = /** @class */ (function () {
  27646. function MaterialDefines() {
  27647. this._isDirty = true;
  27648. this._areLightsDirty = true;
  27649. this._areAttributesDirty = true;
  27650. this._areTexturesDirty = true;
  27651. this._areFresnelDirty = true;
  27652. this._areMiscDirty = true;
  27653. this._areImageProcessingDirty = true;
  27654. this._normals = false;
  27655. this._uvs = false;
  27656. this._needNormals = false;
  27657. this._needUVs = false;
  27658. }
  27659. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  27660. get: function () {
  27661. return this._isDirty;
  27662. },
  27663. enumerable: true,
  27664. configurable: true
  27665. });
  27666. MaterialDefines.prototype.markAsProcessed = function () {
  27667. this._isDirty = false;
  27668. this._areAttributesDirty = false;
  27669. this._areTexturesDirty = false;
  27670. this._areFresnelDirty = false;
  27671. this._areLightsDirty = false;
  27672. this._areMiscDirty = false;
  27673. this._areImageProcessingDirty = false;
  27674. };
  27675. MaterialDefines.prototype.markAsUnprocessed = function () {
  27676. this._isDirty = true;
  27677. };
  27678. MaterialDefines.prototype.markAllAsDirty = function () {
  27679. this._areTexturesDirty = true;
  27680. this._areAttributesDirty = true;
  27681. this._areLightsDirty = true;
  27682. this._areFresnelDirty = true;
  27683. this._areMiscDirty = true;
  27684. this._areImageProcessingDirty = true;
  27685. this._isDirty = true;
  27686. };
  27687. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  27688. this._areImageProcessingDirty = true;
  27689. this._isDirty = true;
  27690. };
  27691. MaterialDefines.prototype.markAsLightDirty = function () {
  27692. this._areLightsDirty = true;
  27693. this._isDirty = true;
  27694. };
  27695. MaterialDefines.prototype.markAsAttributesDirty = function () {
  27696. this._areAttributesDirty = true;
  27697. this._isDirty = true;
  27698. };
  27699. MaterialDefines.prototype.markAsTexturesDirty = function () {
  27700. this._areTexturesDirty = true;
  27701. this._isDirty = true;
  27702. };
  27703. MaterialDefines.prototype.markAsFresnelDirty = function () {
  27704. this._areFresnelDirty = true;
  27705. this._isDirty = true;
  27706. };
  27707. MaterialDefines.prototype.markAsMiscDirty = function () {
  27708. this._areMiscDirty = true;
  27709. this._isDirty = true;
  27710. };
  27711. MaterialDefines.prototype.rebuild = function () {
  27712. if (this._keys) {
  27713. delete this._keys;
  27714. }
  27715. this._keys = [];
  27716. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  27717. var key = _a[_i];
  27718. if (key[0] === "_") {
  27719. continue;
  27720. }
  27721. this._keys.push(key);
  27722. }
  27723. };
  27724. MaterialDefines.prototype.isEqual = function (other) {
  27725. if (this._keys.length !== other._keys.length) {
  27726. return false;
  27727. }
  27728. for (var index = 0; index < this._keys.length; index++) {
  27729. var prop = this._keys[index];
  27730. if (this[prop] !== other[prop]) {
  27731. return false;
  27732. }
  27733. }
  27734. return true;
  27735. };
  27736. MaterialDefines.prototype.cloneTo = function (other) {
  27737. if (this._keys.length !== other._keys.length) {
  27738. other._keys = this._keys.slice(0);
  27739. }
  27740. for (var index = 0; index < this._keys.length; index++) {
  27741. var prop = this._keys[index];
  27742. other[prop] = this[prop];
  27743. }
  27744. };
  27745. MaterialDefines.prototype.reset = function () {
  27746. for (var index = 0; index < this._keys.length; index++) {
  27747. var prop = this._keys[index];
  27748. if (typeof (this[prop]) === "number") {
  27749. this[prop] = 0;
  27750. }
  27751. else {
  27752. this[prop] = false;
  27753. }
  27754. }
  27755. };
  27756. MaterialDefines.prototype.toString = function () {
  27757. var result = "";
  27758. for (var index = 0; index < this._keys.length; index++) {
  27759. var prop = this._keys[index];
  27760. var value = this[prop];
  27761. if (typeof (value) === "number") {
  27762. result += "#define " + prop + " " + this[prop] + "\n";
  27763. }
  27764. else if (value) {
  27765. result += "#define " + prop + "\n";
  27766. }
  27767. }
  27768. return result;
  27769. };
  27770. return MaterialDefines;
  27771. }());
  27772. BABYLON.MaterialDefines = MaterialDefines;
  27773. var Material = /** @class */ (function () {
  27774. function Material(name, scene, doNotAdd) {
  27775. this.checkReadyOnEveryCall = false;
  27776. this.checkReadyOnlyOnce = false;
  27777. this.state = "";
  27778. this.alpha = 1.0;
  27779. this._backFaceCulling = true;
  27780. this.doNotSerialize = false;
  27781. this.storeEffectOnSubMeshes = false;
  27782. /**
  27783. * An event triggered when the material is disposed.
  27784. * @type {BABYLON.Observable}
  27785. */
  27786. this.onDisposeObservable = new BABYLON.Observable();
  27787. /**
  27788. * An event triggered when the material is bound.
  27789. * @type {BABYLON.Observable}
  27790. */
  27791. this.onBindObservable = new BABYLON.Observable();
  27792. /**
  27793. * An event triggered when the material is unbound.
  27794. * @type {BABYLON.Observable}
  27795. */
  27796. this.onUnBindObservable = new BABYLON.Observable();
  27797. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  27798. this._needDepthPrePass = false;
  27799. this.disableDepthWrite = false;
  27800. this.forceDepthWrite = false;
  27801. this.separateCullingPass = false;
  27802. this._fogEnabled = true;
  27803. this.pointSize = 1.0;
  27804. this.zOffset = 0;
  27805. this._wasPreviouslyReady = false;
  27806. this._fillMode = Material.TriangleFillMode;
  27807. this.name = name;
  27808. this.id = name || BABYLON.Tools.RandomId();
  27809. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  27810. if (this._scene.useRightHandedSystem) {
  27811. this.sideOrientation = Material.ClockWiseSideOrientation;
  27812. }
  27813. else {
  27814. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  27815. }
  27816. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  27817. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  27818. if (!doNotAdd) {
  27819. this._scene.materials.push(this);
  27820. }
  27821. }
  27822. Object.defineProperty(Material, "TriangleFillMode", {
  27823. get: function () {
  27824. return Material._TriangleFillMode;
  27825. },
  27826. enumerable: true,
  27827. configurable: true
  27828. });
  27829. Object.defineProperty(Material, "WireFrameFillMode", {
  27830. get: function () {
  27831. return Material._WireFrameFillMode;
  27832. },
  27833. enumerable: true,
  27834. configurable: true
  27835. });
  27836. Object.defineProperty(Material, "PointFillMode", {
  27837. get: function () {
  27838. return Material._PointFillMode;
  27839. },
  27840. enumerable: true,
  27841. configurable: true
  27842. });
  27843. Object.defineProperty(Material, "PointListDrawMode", {
  27844. get: function () {
  27845. return Material._PointListDrawMode;
  27846. },
  27847. enumerable: true,
  27848. configurable: true
  27849. });
  27850. Object.defineProperty(Material, "LineListDrawMode", {
  27851. get: function () {
  27852. return Material._LineListDrawMode;
  27853. },
  27854. enumerable: true,
  27855. configurable: true
  27856. });
  27857. Object.defineProperty(Material, "LineLoopDrawMode", {
  27858. get: function () {
  27859. return Material._LineLoopDrawMode;
  27860. },
  27861. enumerable: true,
  27862. configurable: true
  27863. });
  27864. Object.defineProperty(Material, "LineStripDrawMode", {
  27865. get: function () {
  27866. return Material._LineStripDrawMode;
  27867. },
  27868. enumerable: true,
  27869. configurable: true
  27870. });
  27871. Object.defineProperty(Material, "TriangleStripDrawMode", {
  27872. get: function () {
  27873. return Material._TriangleStripDrawMode;
  27874. },
  27875. enumerable: true,
  27876. configurable: true
  27877. });
  27878. Object.defineProperty(Material, "TriangleFanDrawMode", {
  27879. get: function () {
  27880. return Material._TriangleFanDrawMode;
  27881. },
  27882. enumerable: true,
  27883. configurable: true
  27884. });
  27885. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  27886. get: function () {
  27887. return Material._ClockWiseSideOrientation;
  27888. },
  27889. enumerable: true,
  27890. configurable: true
  27891. });
  27892. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  27893. get: function () {
  27894. return Material._CounterClockWiseSideOrientation;
  27895. },
  27896. enumerable: true,
  27897. configurable: true
  27898. });
  27899. Object.defineProperty(Material, "TextureDirtyFlag", {
  27900. get: function () {
  27901. return Material._TextureDirtyFlag;
  27902. },
  27903. enumerable: true,
  27904. configurable: true
  27905. });
  27906. Object.defineProperty(Material, "LightDirtyFlag", {
  27907. get: function () {
  27908. return Material._LightDirtyFlag;
  27909. },
  27910. enumerable: true,
  27911. configurable: true
  27912. });
  27913. Object.defineProperty(Material, "FresnelDirtyFlag", {
  27914. get: function () {
  27915. return Material._FresnelDirtyFlag;
  27916. },
  27917. enumerable: true,
  27918. configurable: true
  27919. });
  27920. Object.defineProperty(Material, "AttributesDirtyFlag", {
  27921. get: function () {
  27922. return Material._AttributesDirtyFlag;
  27923. },
  27924. enumerable: true,
  27925. configurable: true
  27926. });
  27927. Object.defineProperty(Material, "MiscDirtyFlag", {
  27928. get: function () {
  27929. return Material._MiscDirtyFlag;
  27930. },
  27931. enumerable: true,
  27932. configurable: true
  27933. });
  27934. Object.defineProperty(Material.prototype, "backFaceCulling", {
  27935. get: function () {
  27936. return this._backFaceCulling;
  27937. },
  27938. set: function (value) {
  27939. if (this._backFaceCulling === value) {
  27940. return;
  27941. }
  27942. this._backFaceCulling = value;
  27943. this.markAsDirty(Material.TextureDirtyFlag);
  27944. },
  27945. enumerable: true,
  27946. configurable: true
  27947. });
  27948. Object.defineProperty(Material.prototype, "onDispose", {
  27949. set: function (callback) {
  27950. if (this._onDisposeObserver) {
  27951. this.onDisposeObservable.remove(this._onDisposeObserver);
  27952. }
  27953. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  27954. },
  27955. enumerable: true,
  27956. configurable: true
  27957. });
  27958. Object.defineProperty(Material.prototype, "onBind", {
  27959. set: function (callback) {
  27960. if (this._onBindObserver) {
  27961. this.onBindObservable.remove(this._onBindObserver);
  27962. }
  27963. this._onBindObserver = this.onBindObservable.add(callback);
  27964. },
  27965. enumerable: true,
  27966. configurable: true
  27967. });
  27968. Object.defineProperty(Material.prototype, "alphaMode", {
  27969. get: function () {
  27970. return this._alphaMode;
  27971. },
  27972. set: function (value) {
  27973. if (this._alphaMode === value) {
  27974. return;
  27975. }
  27976. this._alphaMode = value;
  27977. this.markAsDirty(Material.TextureDirtyFlag);
  27978. },
  27979. enumerable: true,
  27980. configurable: true
  27981. });
  27982. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  27983. get: function () {
  27984. return this._needDepthPrePass;
  27985. },
  27986. set: function (value) {
  27987. if (this._needDepthPrePass === value) {
  27988. return;
  27989. }
  27990. this._needDepthPrePass = value;
  27991. if (this._needDepthPrePass) {
  27992. this.checkReadyOnEveryCall = true;
  27993. }
  27994. },
  27995. enumerable: true,
  27996. configurable: true
  27997. });
  27998. Object.defineProperty(Material.prototype, "fogEnabled", {
  27999. get: function () {
  28000. return this._fogEnabled;
  28001. },
  28002. set: function (value) {
  28003. if (this._fogEnabled === value) {
  28004. return;
  28005. }
  28006. this._fogEnabled = value;
  28007. this.markAsDirty(Material.MiscDirtyFlag);
  28008. },
  28009. enumerable: true,
  28010. configurable: true
  28011. });
  28012. Object.defineProperty(Material.prototype, "wireframe", {
  28013. get: function () {
  28014. return this._fillMode === Material.WireFrameFillMode;
  28015. },
  28016. set: function (value) {
  28017. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  28018. },
  28019. enumerable: true,
  28020. configurable: true
  28021. });
  28022. Object.defineProperty(Material.prototype, "pointsCloud", {
  28023. get: function () {
  28024. return this._fillMode === Material.PointFillMode;
  28025. },
  28026. set: function (value) {
  28027. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  28028. },
  28029. enumerable: true,
  28030. configurable: true
  28031. });
  28032. Object.defineProperty(Material.prototype, "fillMode", {
  28033. get: function () {
  28034. return this._fillMode;
  28035. },
  28036. set: function (value) {
  28037. if (this._fillMode === value) {
  28038. return;
  28039. }
  28040. this._fillMode = value;
  28041. this.markAsDirty(Material.MiscDirtyFlag);
  28042. },
  28043. enumerable: true,
  28044. configurable: true
  28045. });
  28046. /**
  28047. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  28048. * subclasses should override adding information pertainent to themselves
  28049. */
  28050. Material.prototype.toString = function (fullDetails) {
  28051. var ret = "Name: " + this.name;
  28052. if (fullDetails) {
  28053. }
  28054. return ret;
  28055. };
  28056. /**
  28057. * Child classes can use it to update shaders
  28058. */
  28059. Material.prototype.getClassName = function () {
  28060. return "Material";
  28061. };
  28062. Object.defineProperty(Material.prototype, "isFrozen", {
  28063. get: function () {
  28064. return this.checkReadyOnlyOnce;
  28065. },
  28066. enumerable: true,
  28067. configurable: true
  28068. });
  28069. Material.prototype.freeze = function () {
  28070. this.checkReadyOnlyOnce = true;
  28071. };
  28072. Material.prototype.unfreeze = function () {
  28073. this.checkReadyOnlyOnce = false;
  28074. };
  28075. Material.prototype.isReady = function (mesh, useInstances) {
  28076. return true;
  28077. };
  28078. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  28079. return false;
  28080. };
  28081. Material.prototype.getEffect = function () {
  28082. return this._effect;
  28083. };
  28084. Material.prototype.getScene = function () {
  28085. return this._scene;
  28086. };
  28087. Material.prototype.needAlphaBlending = function () {
  28088. return (this.alpha < 1.0);
  28089. };
  28090. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  28091. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  28092. };
  28093. Material.prototype.needAlphaTesting = function () {
  28094. return false;
  28095. };
  28096. Material.prototype.getAlphaTestTexture = function () {
  28097. return null;
  28098. };
  28099. Material.prototype.markDirty = function () {
  28100. this._wasPreviouslyReady = false;
  28101. };
  28102. Material.prototype._preBind = function (effect, overrideOrientation) {
  28103. if (overrideOrientation === void 0) { overrideOrientation = null; }
  28104. var engine = this._scene.getEngine();
  28105. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  28106. var reverse = orientation === Material.ClockWiseSideOrientation;
  28107. engine.enableEffect(effect ? effect : this._effect);
  28108. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  28109. return reverse;
  28110. };
  28111. Material.prototype.bind = function (world, mesh) {
  28112. };
  28113. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  28114. };
  28115. Material.prototype.bindOnlyWorldMatrix = function (world) {
  28116. };
  28117. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  28118. sceneUbo.bindToEffect(effect, "Scene");
  28119. };
  28120. Material.prototype.bindView = function (effect) {
  28121. if (!this._useUBO) {
  28122. effect.setMatrix("view", this.getScene().getViewMatrix());
  28123. }
  28124. else {
  28125. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  28126. }
  28127. };
  28128. Material.prototype.bindViewProjection = function (effect) {
  28129. if (!this._useUBO) {
  28130. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  28131. }
  28132. else {
  28133. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  28134. }
  28135. };
  28136. Material.prototype._afterBind = function (mesh) {
  28137. this._scene._cachedMaterial = this;
  28138. if (mesh) {
  28139. this._scene._cachedVisibility = mesh.visibility;
  28140. }
  28141. else {
  28142. this._scene._cachedVisibility = 1;
  28143. }
  28144. if (mesh) {
  28145. this.onBindObservable.notifyObservers(mesh);
  28146. }
  28147. if (this.disableDepthWrite) {
  28148. var engine = this._scene.getEngine();
  28149. this._cachedDepthWriteState = engine.getDepthWrite();
  28150. engine.setDepthWrite(false);
  28151. }
  28152. };
  28153. Material.prototype.unbind = function () {
  28154. this.onUnBindObservable.notifyObservers(this);
  28155. if (this.disableDepthWrite) {
  28156. var engine = this._scene.getEngine();
  28157. engine.setDepthWrite(this._cachedDepthWriteState);
  28158. }
  28159. };
  28160. Material.prototype.getActiveTextures = function () {
  28161. return [];
  28162. };
  28163. Material.prototype.hasTexture = function (texture) {
  28164. return false;
  28165. };
  28166. Material.prototype.clone = function (name) {
  28167. return null;
  28168. };
  28169. Material.prototype.getBindedMeshes = function () {
  28170. var result = new Array();
  28171. for (var index = 0; index < this._scene.meshes.length; index++) {
  28172. var mesh = this._scene.meshes[index];
  28173. if (mesh.material === this) {
  28174. result.push(mesh);
  28175. }
  28176. }
  28177. return result;
  28178. };
  28179. /**
  28180. * Force shader compilation including textures ready check
  28181. */
  28182. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  28183. var _this = this;
  28184. var localOptions = __assign({ alphaTest: null, clipPlane: false }, options);
  28185. var subMesh = new BABYLON.BaseSubMesh();
  28186. var scene = this.getScene();
  28187. var engine = scene.getEngine();
  28188. var checkReady = function () {
  28189. if (!_this._scene || !_this._scene.getEngine()) {
  28190. return;
  28191. }
  28192. if (subMesh._materialDefines) {
  28193. subMesh._materialDefines._renderId = -1;
  28194. }
  28195. var alphaTestState = engine.getAlphaTesting();
  28196. var clipPlaneState = scene.clipPlane;
  28197. engine.setAlphaTesting(localOptions.alphaTest || (!_this.needAlphaBlendingForMesh(mesh) && _this.needAlphaTesting()));
  28198. if (localOptions.clipPlane) {
  28199. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  28200. }
  28201. if (_this.storeEffectOnSubMeshes) {
  28202. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  28203. if (onCompiled) {
  28204. onCompiled(_this);
  28205. }
  28206. }
  28207. else {
  28208. setTimeout(checkReady, 16);
  28209. }
  28210. }
  28211. else {
  28212. if (_this.isReady(mesh)) {
  28213. if (onCompiled) {
  28214. onCompiled(_this);
  28215. }
  28216. }
  28217. else {
  28218. setTimeout(checkReady, 16);
  28219. }
  28220. }
  28221. engine.setAlphaTesting(alphaTestState);
  28222. if (options && options.clipPlane) {
  28223. scene.clipPlane = clipPlaneState;
  28224. }
  28225. };
  28226. checkReady();
  28227. };
  28228. Material.prototype.markAsDirty = function (flag) {
  28229. if (flag & Material.TextureDirtyFlag) {
  28230. this._markAllSubMeshesAsTexturesDirty();
  28231. }
  28232. if (flag & Material.LightDirtyFlag) {
  28233. this._markAllSubMeshesAsLightsDirty();
  28234. }
  28235. if (flag & Material.FresnelDirtyFlag) {
  28236. this._markAllSubMeshesAsFresnelDirty();
  28237. }
  28238. if (flag & Material.AttributesDirtyFlag) {
  28239. this._markAllSubMeshesAsAttributesDirty();
  28240. }
  28241. if (flag & Material.MiscDirtyFlag) {
  28242. this._markAllSubMeshesAsMiscDirty();
  28243. }
  28244. this.getScene().resetCachedMaterial();
  28245. };
  28246. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  28247. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  28248. var mesh = _a[_i];
  28249. if (!mesh.subMeshes) {
  28250. continue;
  28251. }
  28252. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  28253. var subMesh = _c[_b];
  28254. if (subMesh.getMaterial() !== this) {
  28255. continue;
  28256. }
  28257. if (!subMesh._materialDefines) {
  28258. continue;
  28259. }
  28260. func(subMesh._materialDefines);
  28261. }
  28262. }
  28263. };
  28264. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  28265. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  28266. };
  28267. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  28268. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  28269. };
  28270. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  28271. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  28272. };
  28273. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  28274. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  28275. };
  28276. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  28277. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  28278. };
  28279. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  28280. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  28281. };
  28282. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  28283. // Animations
  28284. this.getScene().stopAnimation(this);
  28285. // Remove from scene
  28286. var index = this._scene.materials.indexOf(this);
  28287. if (index >= 0) {
  28288. this._scene.materials.splice(index, 1);
  28289. }
  28290. // Remove from meshes
  28291. for (index = 0; index < this._scene.meshes.length; index++) {
  28292. var mesh = this._scene.meshes[index];
  28293. if (mesh.material === this) {
  28294. mesh.material = null;
  28295. if (mesh.geometry) {
  28296. var geometry = (mesh.geometry);
  28297. if (this.storeEffectOnSubMeshes) {
  28298. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  28299. var subMesh = _a[_i];
  28300. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  28301. if (forceDisposeEffect && subMesh._materialEffect) {
  28302. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  28303. }
  28304. }
  28305. }
  28306. else {
  28307. geometry._releaseVertexArrayObject(this._effect);
  28308. }
  28309. }
  28310. }
  28311. }
  28312. this._uniformBuffer.dispose();
  28313. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  28314. if (forceDisposeEffect && this._effect) {
  28315. if (!this.storeEffectOnSubMeshes) {
  28316. this._scene.getEngine()._releaseEffect(this._effect);
  28317. }
  28318. this._effect = null;
  28319. }
  28320. // Callback
  28321. this.onDisposeObservable.notifyObservers(this);
  28322. this.onDisposeObservable.clear();
  28323. this.onBindObservable.clear();
  28324. this.onUnBindObservable.clear();
  28325. };
  28326. Material.prototype.serialize = function () {
  28327. return BABYLON.SerializationHelper.Serialize(this);
  28328. };
  28329. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  28330. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  28331. multiMaterial.id = parsedMultiMaterial.id;
  28332. if (BABYLON.Tags) {
  28333. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  28334. }
  28335. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  28336. var subMatId = parsedMultiMaterial.materials[matIndex];
  28337. if (subMatId) {
  28338. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  28339. }
  28340. else {
  28341. multiMaterial.subMaterials.push(null);
  28342. }
  28343. }
  28344. return multiMaterial;
  28345. };
  28346. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  28347. if (!parsedMaterial.customType) {
  28348. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  28349. }
  28350. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  28351. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  28352. if (!BABYLON.LegacyPBRMaterial) {
  28353. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  28354. return;
  28355. }
  28356. }
  28357. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  28358. return materialType.Parse(parsedMaterial, scene, rootUrl);
  28359. ;
  28360. };
  28361. // Triangle views
  28362. Material._TriangleFillMode = 0;
  28363. Material._WireFrameFillMode = 1;
  28364. Material._PointFillMode = 2;
  28365. // Draw modes
  28366. Material._PointListDrawMode = 3;
  28367. Material._LineListDrawMode = 4;
  28368. Material._LineLoopDrawMode = 5;
  28369. Material._LineStripDrawMode = 6;
  28370. Material._TriangleStripDrawMode = 7;
  28371. Material._TriangleFanDrawMode = 8;
  28372. Material._ClockWiseSideOrientation = 0;
  28373. Material._CounterClockWiseSideOrientation = 1;
  28374. Material._TextureDirtyFlag = 1;
  28375. Material._LightDirtyFlag = 2;
  28376. Material._FresnelDirtyFlag = 4;
  28377. Material._AttributesDirtyFlag = 8;
  28378. Material._MiscDirtyFlag = 16;
  28379. __decorate([
  28380. BABYLON.serialize()
  28381. ], Material.prototype, "id", void 0);
  28382. __decorate([
  28383. BABYLON.serialize()
  28384. ], Material.prototype, "name", void 0);
  28385. __decorate([
  28386. BABYLON.serialize()
  28387. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  28388. __decorate([
  28389. BABYLON.serialize()
  28390. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  28391. __decorate([
  28392. BABYLON.serialize()
  28393. ], Material.prototype, "state", void 0);
  28394. __decorate([
  28395. BABYLON.serialize()
  28396. ], Material.prototype, "alpha", void 0);
  28397. __decorate([
  28398. BABYLON.serialize("backFaceCulling")
  28399. ], Material.prototype, "_backFaceCulling", void 0);
  28400. __decorate([
  28401. BABYLON.serialize()
  28402. ], Material.prototype, "sideOrientation", void 0);
  28403. __decorate([
  28404. BABYLON.serialize("alphaMode")
  28405. ], Material.prototype, "_alphaMode", void 0);
  28406. __decorate([
  28407. BABYLON.serialize()
  28408. ], Material.prototype, "_needDepthPrePass", void 0);
  28409. __decorate([
  28410. BABYLON.serialize()
  28411. ], Material.prototype, "disableDepthWrite", void 0);
  28412. __decorate([
  28413. BABYLON.serialize()
  28414. ], Material.prototype, "forceDepthWrite", void 0);
  28415. __decorate([
  28416. BABYLON.serialize()
  28417. ], Material.prototype, "separateCullingPass", void 0);
  28418. __decorate([
  28419. BABYLON.serialize("fogEnabled")
  28420. ], Material.prototype, "_fogEnabled", void 0);
  28421. __decorate([
  28422. BABYLON.serialize()
  28423. ], Material.prototype, "pointSize", void 0);
  28424. __decorate([
  28425. BABYLON.serialize()
  28426. ], Material.prototype, "zOffset", void 0);
  28427. __decorate([
  28428. BABYLON.serialize()
  28429. ], Material.prototype, "wireframe", null);
  28430. __decorate([
  28431. BABYLON.serialize()
  28432. ], Material.prototype, "pointsCloud", null);
  28433. __decorate([
  28434. BABYLON.serialize()
  28435. ], Material.prototype, "fillMode", null);
  28436. return Material;
  28437. }());
  28438. BABYLON.Material = Material;
  28439. })(BABYLON || (BABYLON = {}));
  28440. //# sourceMappingURL=babylon.material.js.map
  28441. var BABYLON;
  28442. (function (BABYLON) {
  28443. var UniformBuffer = /** @class */ (function () {
  28444. /**
  28445. * Uniform buffer objects.
  28446. *
  28447. * Handles blocks of uniform on the GPU.
  28448. *
  28449. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  28450. *
  28451. * For more information, please refer to :
  28452. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  28453. */
  28454. function UniformBuffer(engine, data, dynamic) {
  28455. this._engine = engine;
  28456. this._noUBO = !engine.supportsUniformBuffers;
  28457. this._dynamic = dynamic;
  28458. this._data = data || [];
  28459. this._uniformLocations = {};
  28460. this._uniformSizes = {};
  28461. this._uniformLocationPointer = 0;
  28462. this._needSync = false;
  28463. if (this._noUBO) {
  28464. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  28465. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  28466. this.updateFloat = this._updateFloatForEffect;
  28467. this.updateFloat2 = this._updateFloat2ForEffect;
  28468. this.updateFloat3 = this._updateFloat3ForEffect;
  28469. this.updateFloat4 = this._updateFloat4ForEffect;
  28470. this.updateMatrix = this._updateMatrixForEffect;
  28471. this.updateVector3 = this._updateVector3ForEffect;
  28472. this.updateVector4 = this._updateVector4ForEffect;
  28473. this.updateColor3 = this._updateColor3ForEffect;
  28474. this.updateColor4 = this._updateColor4ForEffect;
  28475. }
  28476. else {
  28477. this._engine._uniformBuffers.push(this);
  28478. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  28479. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  28480. this.updateFloat = this._updateFloatForUniform;
  28481. this.updateFloat2 = this._updateFloat2ForUniform;
  28482. this.updateFloat3 = this._updateFloat3ForUniform;
  28483. this.updateFloat4 = this._updateFloat4ForUniform;
  28484. this.updateMatrix = this._updateMatrixForUniform;
  28485. this.updateVector3 = this._updateVector3ForUniform;
  28486. this.updateVector4 = this._updateVector4ForUniform;
  28487. this.updateColor3 = this._updateColor3ForUniform;
  28488. this.updateColor4 = this._updateColor4ForUniform;
  28489. }
  28490. }
  28491. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  28492. // Properties
  28493. /**
  28494. * Indicates if the buffer is using the WebGL2 UBO implementation,
  28495. * or just falling back on setUniformXXX calls.
  28496. */
  28497. get: function () {
  28498. return !this._noUBO;
  28499. },
  28500. enumerable: true,
  28501. configurable: true
  28502. });
  28503. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  28504. /**
  28505. * Indicates if the WebGL underlying uniform buffer is in sync
  28506. * with the javascript cache data.
  28507. */
  28508. get: function () {
  28509. return !this._needSync;
  28510. },
  28511. enumerable: true,
  28512. configurable: true
  28513. });
  28514. /**
  28515. * Indicates if the WebGL underlying uniform buffer is dynamic.
  28516. * Also, a dynamic UniformBuffer will disable cache verification and always
  28517. * update the underlying WebGL uniform buffer to the GPU.
  28518. */
  28519. UniformBuffer.prototype.isDynamic = function () {
  28520. return this._dynamic !== undefined;
  28521. };
  28522. /**
  28523. * The data cache on JS side.
  28524. */
  28525. UniformBuffer.prototype.getData = function () {
  28526. return this._bufferData;
  28527. };
  28528. /**
  28529. * The underlying WebGL Uniform buffer.
  28530. */
  28531. UniformBuffer.prototype.getBuffer = function () {
  28532. return this._buffer;
  28533. };
  28534. /**
  28535. * std140 layout specifies how to align data within an UBO structure.
  28536. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  28537. * for specs.
  28538. */
  28539. UniformBuffer.prototype._fillAlignment = function (size) {
  28540. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  28541. // and 4x4 matrices
  28542. // TODO : change if other types are used
  28543. var alignment;
  28544. if (size <= 2) {
  28545. alignment = size;
  28546. }
  28547. else {
  28548. alignment = 4;
  28549. }
  28550. if ((this._uniformLocationPointer % alignment) !== 0) {
  28551. var oldPointer = this._uniformLocationPointer;
  28552. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  28553. var diff = this._uniformLocationPointer - oldPointer;
  28554. for (var i = 0; i < diff; i++) {
  28555. this._data.push(0);
  28556. }
  28557. }
  28558. };
  28559. /**
  28560. * Adds an uniform in the buffer.
  28561. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  28562. * for the layout to be correct !
  28563. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28564. * @param {number|number[]} size Data size, or data directly.
  28565. */
  28566. UniformBuffer.prototype.addUniform = function (name, size) {
  28567. if (this._noUBO) {
  28568. return;
  28569. }
  28570. if (this._uniformLocations[name] !== undefined) {
  28571. // Already existing uniform
  28572. return;
  28573. }
  28574. // This function must be called in the order of the shader layout !
  28575. // size can be the size of the uniform, or data directly
  28576. var data;
  28577. if (size instanceof Array) {
  28578. data = size;
  28579. size = data.length;
  28580. }
  28581. else {
  28582. size = size;
  28583. data = [];
  28584. // Fill with zeros
  28585. for (var i = 0; i < size; i++) {
  28586. data.push(0);
  28587. }
  28588. }
  28589. this._fillAlignment(size);
  28590. this._uniformSizes[name] = size;
  28591. this._uniformLocations[name] = this._uniformLocationPointer;
  28592. this._uniformLocationPointer += size;
  28593. for (var i = 0; i < size; i++) {
  28594. this._data.push(data[i]);
  28595. }
  28596. this._needSync = true;
  28597. };
  28598. /**
  28599. * Wrapper for addUniform.
  28600. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28601. * @param {Matrix} mat A 4x4 matrix.
  28602. */
  28603. UniformBuffer.prototype.addMatrix = function (name, mat) {
  28604. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  28605. };
  28606. /**
  28607. * Wrapper for addUniform.
  28608. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28609. * @param {number} x
  28610. * @param {number} y
  28611. */
  28612. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  28613. var temp = [x, y];
  28614. this.addUniform(name, temp);
  28615. };
  28616. /**
  28617. * Wrapper for addUniform.
  28618. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28619. * @param {number} x
  28620. * @param {number} y
  28621. * @param {number} z
  28622. */
  28623. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  28624. var temp = [x, y, z];
  28625. this.addUniform(name, temp);
  28626. };
  28627. /**
  28628. * Wrapper for addUniform.
  28629. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28630. * @param {Color3} color
  28631. */
  28632. UniformBuffer.prototype.addColor3 = function (name, color) {
  28633. var temp = new Array();
  28634. color.toArray(temp);
  28635. this.addUniform(name, temp);
  28636. };
  28637. /**
  28638. * Wrapper for addUniform.
  28639. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28640. * @param {Color3} color
  28641. * @param {number} alpha
  28642. */
  28643. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  28644. var temp = new Array();
  28645. color.toArray(temp);
  28646. temp.push(alpha);
  28647. this.addUniform(name, temp);
  28648. };
  28649. /**
  28650. * Wrapper for addUniform.
  28651. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28652. * @param {Vector3} vector
  28653. */
  28654. UniformBuffer.prototype.addVector3 = function (name, vector) {
  28655. var temp = new Array();
  28656. vector.toArray(temp);
  28657. this.addUniform(name, temp);
  28658. };
  28659. /**
  28660. * Wrapper for addUniform.
  28661. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28662. */
  28663. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  28664. this.addUniform(name, 12);
  28665. };
  28666. /**
  28667. * Wrapper for addUniform.
  28668. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  28669. */
  28670. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  28671. this.addUniform(name, 8);
  28672. };
  28673. /**
  28674. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  28675. */
  28676. UniformBuffer.prototype.create = function () {
  28677. if (this._noUBO) {
  28678. return;
  28679. }
  28680. if (this._buffer) {
  28681. return; // nothing to do
  28682. }
  28683. // See spec, alignment must be filled as a vec4
  28684. this._fillAlignment(4);
  28685. this._bufferData = new Float32Array(this._data);
  28686. this._rebuild();
  28687. this._needSync = true;
  28688. };
  28689. UniformBuffer.prototype._rebuild = function () {
  28690. if (this._noUBO) {
  28691. return;
  28692. }
  28693. if (this._dynamic) {
  28694. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  28695. }
  28696. else {
  28697. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  28698. }
  28699. };
  28700. /**
  28701. * Updates the WebGL Uniform Buffer on the GPU.
  28702. * If the `dynamic` flag is set to true, no cache comparison is done.
  28703. * Otherwise, the buffer will be updated only if the cache differs.
  28704. */
  28705. UniformBuffer.prototype.update = function () {
  28706. if (!this._buffer) {
  28707. this.create();
  28708. return;
  28709. }
  28710. if (!this._dynamic && !this._needSync) {
  28711. return;
  28712. }
  28713. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  28714. this._needSync = false;
  28715. };
  28716. /**
  28717. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  28718. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  28719. * @param {number[]|Float32Array} data Flattened data
  28720. * @param {number} size Size of the data.
  28721. */
  28722. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  28723. var location = this._uniformLocations[uniformName];
  28724. if (location === undefined) {
  28725. if (this._buffer) {
  28726. // Cannot add an uniform if the buffer is already created
  28727. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  28728. return;
  28729. }
  28730. this.addUniform(uniformName, size);
  28731. location = this._uniformLocations[uniformName];
  28732. }
  28733. if (!this._buffer) {
  28734. this.create();
  28735. }
  28736. if (!this._dynamic) {
  28737. // Cache for static uniform buffers
  28738. var changed = false;
  28739. for (var i = 0; i < size; i++) {
  28740. if (this._bufferData[location + i] !== data[i]) {
  28741. changed = true;
  28742. this._bufferData[location + i] = data[i];
  28743. }
  28744. }
  28745. this._needSync = this._needSync || changed;
  28746. }
  28747. else {
  28748. // No cache for dynamic
  28749. for (var i = 0; i < size; i++) {
  28750. this._bufferData[location + i] = data[i];
  28751. }
  28752. }
  28753. };
  28754. // Update methods
  28755. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  28756. // To match std140, matrix must be realigned
  28757. for (var i = 0; i < 3; i++) {
  28758. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  28759. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  28760. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  28761. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  28762. }
  28763. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  28764. };
  28765. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  28766. this._currentEffect.setMatrix3x3(name, matrix);
  28767. };
  28768. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  28769. this._currentEffect.setMatrix2x2(name, matrix);
  28770. };
  28771. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  28772. // To match std140, matrix must be realigned
  28773. for (var i = 0; i < 2; i++) {
  28774. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  28775. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  28776. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  28777. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  28778. }
  28779. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  28780. };
  28781. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  28782. this._currentEffect.setFloat(name, x);
  28783. };
  28784. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  28785. UniformBuffer._tempBuffer[0] = x;
  28786. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  28787. };
  28788. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  28789. if (suffix === void 0) { suffix = ""; }
  28790. this._currentEffect.setFloat2(name + suffix, x, y);
  28791. };
  28792. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  28793. if (suffix === void 0) { suffix = ""; }
  28794. UniformBuffer._tempBuffer[0] = x;
  28795. UniformBuffer._tempBuffer[1] = y;
  28796. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  28797. };
  28798. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  28799. if (suffix === void 0) { suffix = ""; }
  28800. this._currentEffect.setFloat3(name + suffix, x, y, z);
  28801. };
  28802. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  28803. if (suffix === void 0) { suffix = ""; }
  28804. UniformBuffer._tempBuffer[0] = x;
  28805. UniformBuffer._tempBuffer[1] = y;
  28806. UniformBuffer._tempBuffer[2] = z;
  28807. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  28808. };
  28809. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  28810. if (suffix === void 0) { suffix = ""; }
  28811. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  28812. };
  28813. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  28814. if (suffix === void 0) { suffix = ""; }
  28815. UniformBuffer._tempBuffer[0] = x;
  28816. UniformBuffer._tempBuffer[1] = y;
  28817. UniformBuffer._tempBuffer[2] = z;
  28818. UniformBuffer._tempBuffer[3] = w;
  28819. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  28820. };
  28821. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  28822. this._currentEffect.setMatrix(name, mat);
  28823. };
  28824. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  28825. this.updateUniform(name, mat.toArray(), 16);
  28826. };
  28827. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  28828. this._currentEffect.setVector3(name, vector);
  28829. };
  28830. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  28831. vector.toArray(UniformBuffer._tempBuffer);
  28832. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  28833. };
  28834. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  28835. this._currentEffect.setVector4(name, vector);
  28836. };
  28837. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  28838. vector.toArray(UniformBuffer._tempBuffer);
  28839. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  28840. };
  28841. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  28842. if (suffix === void 0) { suffix = ""; }
  28843. this._currentEffect.setColor3(name + suffix, color);
  28844. };
  28845. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  28846. if (suffix === void 0) { suffix = ""; }
  28847. color.toArray(UniformBuffer._tempBuffer);
  28848. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  28849. };
  28850. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  28851. if (suffix === void 0) { suffix = ""; }
  28852. this._currentEffect.setColor4(name + suffix, color, alpha);
  28853. };
  28854. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  28855. if (suffix === void 0) { suffix = ""; }
  28856. color.toArray(UniformBuffer._tempBuffer);
  28857. UniformBuffer._tempBuffer[3] = alpha;
  28858. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  28859. };
  28860. /**
  28861. * Sets a sampler uniform on the effect.
  28862. * @param {string} name Name of the sampler.
  28863. * @param {Texture} texture
  28864. */
  28865. UniformBuffer.prototype.setTexture = function (name, texture) {
  28866. this._currentEffect.setTexture(name, texture);
  28867. };
  28868. /**
  28869. * Directly updates the value of the uniform in the cache AND on the GPU.
  28870. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  28871. * @param {number[]|Float32Array} data Flattened data
  28872. */
  28873. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  28874. this.updateUniform(uniformName, data, data.length);
  28875. this.update();
  28876. };
  28877. /**
  28878. * Binds this uniform buffer to an effect.
  28879. * @param {Effect} effect
  28880. * @param {string} name Name of the uniform block in the shader.
  28881. */
  28882. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  28883. this._currentEffect = effect;
  28884. if (this._noUBO || !this._buffer) {
  28885. return;
  28886. }
  28887. effect.bindUniformBuffer(this._buffer, name);
  28888. };
  28889. /**
  28890. * Disposes the uniform buffer.
  28891. */
  28892. UniformBuffer.prototype.dispose = function () {
  28893. if (this._noUBO) {
  28894. return;
  28895. }
  28896. var index = this._engine._uniformBuffers.indexOf(this);
  28897. if (index !== -1) {
  28898. this._engine._uniformBuffers.splice(index, 1);
  28899. }
  28900. if (!this._buffer) {
  28901. return;
  28902. }
  28903. if (this._engine._releaseBuffer(this._buffer)) {
  28904. this._buffer = null;
  28905. }
  28906. };
  28907. // Pool for avoiding memory leaks
  28908. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  28909. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  28910. return UniformBuffer;
  28911. }());
  28912. BABYLON.UniformBuffer = UniformBuffer;
  28913. })(BABYLON || (BABYLON = {}));
  28914. //# sourceMappingURL=babylon.uniformBuffer.js.map
  28915. var BABYLON;
  28916. (function (BABYLON) {
  28917. var VertexData = /** @class */ (function () {
  28918. function VertexData() {
  28919. }
  28920. VertexData.prototype.set = function (data, kind) {
  28921. switch (kind) {
  28922. case BABYLON.VertexBuffer.PositionKind:
  28923. this.positions = data;
  28924. break;
  28925. case BABYLON.VertexBuffer.NormalKind:
  28926. this.normals = data;
  28927. break;
  28928. case BABYLON.VertexBuffer.TangentKind:
  28929. this.tangents = data;
  28930. break;
  28931. case BABYLON.VertexBuffer.UVKind:
  28932. this.uvs = data;
  28933. break;
  28934. case BABYLON.VertexBuffer.UV2Kind:
  28935. this.uvs2 = data;
  28936. break;
  28937. case BABYLON.VertexBuffer.UV3Kind:
  28938. this.uvs3 = data;
  28939. break;
  28940. case BABYLON.VertexBuffer.UV4Kind:
  28941. this.uvs4 = data;
  28942. break;
  28943. case BABYLON.VertexBuffer.UV5Kind:
  28944. this.uvs5 = data;
  28945. break;
  28946. case BABYLON.VertexBuffer.UV6Kind:
  28947. this.uvs6 = data;
  28948. break;
  28949. case BABYLON.VertexBuffer.ColorKind:
  28950. this.colors = data;
  28951. break;
  28952. case BABYLON.VertexBuffer.MatricesIndicesKind:
  28953. this.matricesIndices = data;
  28954. break;
  28955. case BABYLON.VertexBuffer.MatricesWeightsKind:
  28956. this.matricesWeights = data;
  28957. break;
  28958. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  28959. this.matricesIndicesExtra = data;
  28960. break;
  28961. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  28962. this.matricesWeightsExtra = data;
  28963. break;
  28964. }
  28965. };
  28966. /**
  28967. * Associates the vertexData to the passed Mesh.
  28968. * Sets it as updatable or not (default `false`).
  28969. * Returns the VertexData.
  28970. */
  28971. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  28972. this._applyTo(mesh, updatable);
  28973. return this;
  28974. };
  28975. /**
  28976. * Associates the vertexData to the passed Geometry.
  28977. * Sets it as updatable or not (default `false`).
  28978. * Returns the VertexData.
  28979. */
  28980. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  28981. this._applyTo(geometry, updatable);
  28982. return this;
  28983. };
  28984. /**
  28985. * Updates the associated mesh.
  28986. * Returns the VertexData.
  28987. */
  28988. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  28989. this._update(mesh);
  28990. return this;
  28991. };
  28992. /**
  28993. * Updates the associated geometry.
  28994. * Returns the VertexData.
  28995. */
  28996. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  28997. this._update(geometry);
  28998. return this;
  28999. };
  29000. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  29001. if (updatable === void 0) { updatable = false; }
  29002. if (this.positions) {
  29003. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  29004. }
  29005. if (this.normals) {
  29006. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  29007. }
  29008. if (this.tangents) {
  29009. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  29010. }
  29011. if (this.uvs) {
  29012. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  29013. }
  29014. if (this.uvs2) {
  29015. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  29016. }
  29017. if (this.uvs3) {
  29018. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  29019. }
  29020. if (this.uvs4) {
  29021. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  29022. }
  29023. if (this.uvs5) {
  29024. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  29025. }
  29026. if (this.uvs6) {
  29027. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  29028. }
  29029. if (this.colors) {
  29030. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  29031. }
  29032. if (this.matricesIndices) {
  29033. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  29034. }
  29035. if (this.matricesWeights) {
  29036. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  29037. }
  29038. if (this.matricesIndicesExtra) {
  29039. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  29040. }
  29041. if (this.matricesWeightsExtra) {
  29042. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  29043. }
  29044. if (this.indices) {
  29045. meshOrGeometry.setIndices(this.indices, null, updatable);
  29046. }
  29047. return this;
  29048. };
  29049. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  29050. if (this.positions) {
  29051. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  29052. }
  29053. if (this.normals) {
  29054. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  29055. }
  29056. if (this.tangents) {
  29057. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  29058. }
  29059. if (this.uvs) {
  29060. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  29061. }
  29062. if (this.uvs2) {
  29063. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  29064. }
  29065. if (this.uvs3) {
  29066. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  29067. }
  29068. if (this.uvs4) {
  29069. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  29070. }
  29071. if (this.uvs5) {
  29072. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  29073. }
  29074. if (this.uvs6) {
  29075. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  29076. }
  29077. if (this.colors) {
  29078. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  29079. }
  29080. if (this.matricesIndices) {
  29081. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  29082. }
  29083. if (this.matricesWeights) {
  29084. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  29085. }
  29086. if (this.matricesIndicesExtra) {
  29087. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  29088. }
  29089. if (this.matricesWeightsExtra) {
  29090. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  29091. }
  29092. if (this.indices) {
  29093. meshOrGeometry.setIndices(this.indices, null);
  29094. }
  29095. return this;
  29096. };
  29097. /**
  29098. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  29099. * Returns the VertexData.
  29100. */
  29101. VertexData.prototype.transform = function (matrix) {
  29102. var transformed = BABYLON.Vector3.Zero();
  29103. var index;
  29104. if (this.positions) {
  29105. var position = BABYLON.Vector3.Zero();
  29106. for (index = 0; index < this.positions.length; index += 3) {
  29107. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  29108. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  29109. this.positions[index] = transformed.x;
  29110. this.positions[index + 1] = transformed.y;
  29111. this.positions[index + 2] = transformed.z;
  29112. }
  29113. }
  29114. if (this.normals) {
  29115. var normal = BABYLON.Vector3.Zero();
  29116. for (index = 0; index < this.normals.length; index += 3) {
  29117. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  29118. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  29119. this.normals[index] = transformed.x;
  29120. this.normals[index + 1] = transformed.y;
  29121. this.normals[index + 2] = transformed.z;
  29122. }
  29123. }
  29124. if (this.tangents) {
  29125. var tangent = BABYLON.Vector4.Zero();
  29126. var tangentTransformed = BABYLON.Vector4.Zero();
  29127. for (index = 0; index < this.tangents.length; index += 4) {
  29128. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  29129. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  29130. this.tangents[index] = tangentTransformed.x;
  29131. this.tangents[index + 1] = tangentTransformed.y;
  29132. this.tangents[index + 2] = tangentTransformed.z;
  29133. this.tangents[index + 3] = tangentTransformed.w;
  29134. }
  29135. }
  29136. return this;
  29137. };
  29138. /**
  29139. * Merges the passed VertexData into the current one.
  29140. * Returns the modified VertexData.
  29141. */
  29142. VertexData.prototype.merge = function (other, options) {
  29143. options = options || {};
  29144. if (other.indices) {
  29145. if (!this.indices) {
  29146. this.indices = [];
  29147. }
  29148. var offset = this.positions ? this.positions.length / 3 : 0;
  29149. for (var index = 0; index < other.indices.length; index++) {
  29150. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  29151. this.indices.push(other.indices[index] + offset);
  29152. }
  29153. }
  29154. this.positions = this._mergeElement(this.positions, other.positions);
  29155. if (!this.positions) {
  29156. return this;
  29157. }
  29158. var count = this.positions.length / 3;
  29159. this.normals = this._mergeElement(this.normals, other.normals, count * 3);
  29160. this.tangents = this._mergeElement(this.tangents, other.tangents, count * (options.tangentLength || 4));
  29161. this.uvs = this._mergeElement(this.uvs, other.uvs, count * 2);
  29162. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2, count * 2);
  29163. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3, count * 2);
  29164. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4, count * 2);
  29165. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5, count * 2);
  29166. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6, count * 2);
  29167. this.colors = this._mergeElement(this.colors, other.colors, count * 4, 1);
  29168. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices, count * 4);
  29169. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights, count * 4);
  29170. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra, count * 4);
  29171. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra, count * 4);
  29172. return this;
  29173. };
  29174. VertexData.prototype._mergeElement = function (source, other, length, defaultValue) {
  29175. if (length === void 0) { length = 0; }
  29176. if (defaultValue === void 0) { defaultValue = 0; }
  29177. if (!other && !source) {
  29178. return null;
  29179. }
  29180. if (!other) {
  29181. var padding = new Float32Array(source.length);
  29182. padding.fill(defaultValue);
  29183. return this._mergeElement(source, padding, length);
  29184. }
  29185. if (!source) {
  29186. if (length === 0 || length === other.length) {
  29187. return other;
  29188. }
  29189. var padding = new Float32Array(length - other.length);
  29190. padding.fill(defaultValue);
  29191. return this._mergeElement(padding, other, length);
  29192. }
  29193. var len = other.length + source.length;
  29194. var isSrcTypedArray = source instanceof Float32Array;
  29195. var isOthTypedArray = other instanceof Float32Array;
  29196. // use non-loop method when the source is Float32Array
  29197. if (isSrcTypedArray) {
  29198. var ret32 = new Float32Array(len);
  29199. ret32.set(source);
  29200. ret32.set(other, source.length);
  29201. return ret32;
  29202. // source is number[], when other is also use concat
  29203. }
  29204. else if (!isOthTypedArray) {
  29205. return source.concat(other);
  29206. // source is a number[], but other is a Float32Array, loop required
  29207. }
  29208. else {
  29209. var ret = source.slice(0); // copy source to a separate array
  29210. for (var i = 0, len = other.length; i < len; i++) {
  29211. ret.push(other[i]);
  29212. }
  29213. return ret;
  29214. }
  29215. };
  29216. /**
  29217. * Serializes the VertexData.
  29218. * Returns a serialized object.
  29219. */
  29220. VertexData.prototype.serialize = function () {
  29221. var serializationObject = this.serialize();
  29222. if (this.positions) {
  29223. serializationObject.positions = this.positions;
  29224. }
  29225. if (this.normals) {
  29226. serializationObject.normals = this.normals;
  29227. }
  29228. if (this.tangents) {
  29229. serializationObject.tangents = this.tangents;
  29230. }
  29231. if (this.uvs) {
  29232. serializationObject.uvs = this.uvs;
  29233. }
  29234. if (this.uvs2) {
  29235. serializationObject.uvs2 = this.uvs2;
  29236. }
  29237. if (this.uvs3) {
  29238. serializationObject.uvs3 = this.uvs3;
  29239. }
  29240. if (this.uvs4) {
  29241. serializationObject.uvs4 = this.uvs4;
  29242. }
  29243. if (this.uvs5) {
  29244. serializationObject.uvs5 = this.uvs5;
  29245. }
  29246. if (this.uvs6) {
  29247. serializationObject.uvs6 = this.uvs6;
  29248. }
  29249. if (this.colors) {
  29250. serializationObject.colors = this.colors;
  29251. }
  29252. if (this.matricesIndices) {
  29253. serializationObject.matricesIndices = this.matricesIndices;
  29254. serializationObject.matricesIndices._isExpanded = true;
  29255. }
  29256. if (this.matricesWeights) {
  29257. serializationObject.matricesWeights = this.matricesWeights;
  29258. }
  29259. if (this.matricesIndicesExtra) {
  29260. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  29261. serializationObject.matricesIndicesExtra._isExpanded = true;
  29262. }
  29263. if (this.matricesWeightsExtra) {
  29264. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  29265. }
  29266. serializationObject.indices = this.indices;
  29267. return serializationObject;
  29268. };
  29269. // Statics
  29270. /**
  29271. * Returns the object VertexData associated to the passed mesh.
  29272. */
  29273. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  29274. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  29275. };
  29276. /**
  29277. * Returns the object VertexData associated to the passed geometry.
  29278. */
  29279. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  29280. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  29281. };
  29282. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  29283. var result = new VertexData();
  29284. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  29285. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  29286. }
  29287. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  29288. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  29289. }
  29290. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  29291. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  29292. }
  29293. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  29294. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  29295. }
  29296. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  29297. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  29298. }
  29299. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  29300. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  29301. }
  29302. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  29303. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  29304. }
  29305. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  29306. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  29307. }
  29308. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  29309. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  29310. }
  29311. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  29312. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  29313. }
  29314. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  29315. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  29316. }
  29317. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  29318. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  29319. }
  29320. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  29321. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  29322. }
  29323. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  29324. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  29325. }
  29326. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  29327. return result;
  29328. };
  29329. /**
  29330. * Creates the vertexData of the Ribbon.
  29331. */
  29332. VertexData.CreateRibbon = function (options) {
  29333. var pathArray = options.pathArray;
  29334. var closeArray = options.closeArray || false;
  29335. var closePath = options.closePath || false;
  29336. var invertUV = options.invertUV || false;
  29337. var defaultOffset = Math.floor(pathArray[0].length / 2);
  29338. var offset = options.offset || defaultOffset;
  29339. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  29340. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29341. var customUV = options.uvs;
  29342. var customColors = options.colors;
  29343. var positions = [];
  29344. var indices = [];
  29345. var normals = [];
  29346. var uvs = [];
  29347. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  29348. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  29349. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  29350. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  29351. var minlg; // minimal length among all paths from pathArray
  29352. var lg = []; // array of path lengths : nb of vertex per path
  29353. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  29354. var p; // path iterator
  29355. var i; // point iterator
  29356. var j; // point iterator
  29357. // if single path in pathArray
  29358. if (pathArray.length < 2) {
  29359. var ar1 = [];
  29360. var ar2 = [];
  29361. for (i = 0; i < pathArray[0].length - offset; i++) {
  29362. ar1.push(pathArray[0][i]);
  29363. ar2.push(pathArray[0][i + offset]);
  29364. }
  29365. pathArray = [ar1, ar2];
  29366. }
  29367. // positions and horizontal distances (u)
  29368. var idc = 0;
  29369. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  29370. var path;
  29371. var l;
  29372. minlg = pathArray[0].length;
  29373. var vectlg;
  29374. var dist;
  29375. for (p = 0; p < pathArray.length; p++) {
  29376. uTotalDistance[p] = 0;
  29377. us[p] = [0];
  29378. path = pathArray[p];
  29379. l = path.length;
  29380. minlg = (minlg < l) ? minlg : l;
  29381. j = 0;
  29382. while (j < l) {
  29383. positions.push(path[j].x, path[j].y, path[j].z);
  29384. if (j > 0) {
  29385. vectlg = path[j].subtract(path[j - 1]).length();
  29386. dist = vectlg + uTotalDistance[p];
  29387. us[p].push(dist);
  29388. uTotalDistance[p] = dist;
  29389. }
  29390. j++;
  29391. }
  29392. if (closePath) {
  29393. j--;
  29394. positions.push(path[0].x, path[0].y, path[0].z);
  29395. vectlg = path[j].subtract(path[0]).length();
  29396. dist = vectlg + uTotalDistance[p];
  29397. us[p].push(dist);
  29398. uTotalDistance[p] = dist;
  29399. }
  29400. lg[p] = l + closePathCorr;
  29401. idx[p] = idc;
  29402. idc += (l + closePathCorr);
  29403. }
  29404. // vertical distances (v)
  29405. var path1;
  29406. var path2;
  29407. var vertex1 = null;
  29408. var vertex2 = null;
  29409. for (i = 0; i < minlg + closePathCorr; i++) {
  29410. vTotalDistance[i] = 0;
  29411. vs[i] = [0];
  29412. for (p = 0; p < pathArray.length - 1; p++) {
  29413. path1 = pathArray[p];
  29414. path2 = pathArray[p + 1];
  29415. if (i === minlg) {
  29416. vertex1 = path1[0];
  29417. vertex2 = path2[0];
  29418. }
  29419. else {
  29420. vertex1 = path1[i];
  29421. vertex2 = path2[i];
  29422. }
  29423. vectlg = vertex2.subtract(vertex1).length();
  29424. dist = vectlg + vTotalDistance[i];
  29425. vs[i].push(dist);
  29426. vTotalDistance[i] = dist;
  29427. }
  29428. if (closeArray && vertex2 && vertex1) {
  29429. path1 = pathArray[p];
  29430. path2 = pathArray[0];
  29431. if (i === minlg) {
  29432. vertex2 = path2[0];
  29433. }
  29434. vectlg = vertex2.subtract(vertex1).length();
  29435. dist = vectlg + vTotalDistance[i];
  29436. vTotalDistance[i] = dist;
  29437. }
  29438. }
  29439. // uvs
  29440. var u;
  29441. var v;
  29442. if (customUV) {
  29443. for (p = 0; p < customUV.length; p++) {
  29444. uvs.push(customUV[p].x, customUV[p].y);
  29445. }
  29446. }
  29447. else {
  29448. for (p = 0; p < pathArray.length; p++) {
  29449. for (i = 0; i < minlg + closePathCorr; i++) {
  29450. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  29451. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  29452. if (invertUV) {
  29453. uvs.push(v, u);
  29454. }
  29455. else {
  29456. uvs.push(u, v);
  29457. }
  29458. }
  29459. }
  29460. }
  29461. // indices
  29462. p = 0; // path index
  29463. var pi = 0; // positions array index
  29464. var l1 = lg[p] - 1; // path1 length
  29465. var l2 = lg[p + 1] - 1; // path2 length
  29466. var min = (l1 < l2) ? l1 : l2; // current path stop index
  29467. var shft = idx[1] - idx[0]; // shift
  29468. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  29469. while (pi <= min && p < path1nb) {
  29470. // 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
  29471. indices.push(pi, pi + shft, pi + 1);
  29472. indices.push(pi + shft + 1, pi + 1, pi + shft);
  29473. pi += 1;
  29474. if (pi === min) {
  29475. p++;
  29476. if (p === lg.length - 1) {
  29477. shft = idx[0] - idx[p];
  29478. l1 = lg[p] - 1;
  29479. l2 = lg[0] - 1;
  29480. }
  29481. else {
  29482. shft = idx[p + 1] - idx[p];
  29483. l1 = lg[p] - 1;
  29484. l2 = lg[p + 1] - 1;
  29485. }
  29486. pi = idx[p];
  29487. min = (l1 < l2) ? l1 + pi : l2 + pi;
  29488. }
  29489. }
  29490. // normals
  29491. VertexData.ComputeNormals(positions, indices, normals);
  29492. if (closePath) {
  29493. var indexFirst = 0;
  29494. var indexLast = 0;
  29495. for (p = 0; p < pathArray.length; p++) {
  29496. indexFirst = idx[p] * 3;
  29497. if (p + 1 < pathArray.length) {
  29498. indexLast = (idx[p + 1] - 1) * 3;
  29499. }
  29500. else {
  29501. indexLast = normals.length - 3;
  29502. }
  29503. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  29504. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  29505. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  29506. normals[indexLast] = normals[indexFirst];
  29507. normals[indexLast + 1] = normals[indexFirst + 1];
  29508. normals[indexLast + 2] = normals[indexFirst + 2];
  29509. }
  29510. }
  29511. // sides
  29512. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29513. // Colors
  29514. var colors = null;
  29515. if (customColors) {
  29516. colors = new Float32Array(customColors.length * 4);
  29517. for (var c = 0; c < customColors.length; c++) {
  29518. colors[c * 4] = customColors[c].r;
  29519. colors[c * 4 + 1] = customColors[c].g;
  29520. colors[c * 4 + 2] = customColors[c].b;
  29521. colors[c * 4 + 3] = customColors[c].a;
  29522. }
  29523. }
  29524. // Result
  29525. var vertexData = new VertexData();
  29526. var positions32 = new Float32Array(positions);
  29527. var normals32 = new Float32Array(normals);
  29528. var uvs32 = new Float32Array(uvs);
  29529. vertexData.indices = indices;
  29530. vertexData.positions = positions32;
  29531. vertexData.normals = normals32;
  29532. vertexData.uvs = uvs32;
  29533. if (colors) {
  29534. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  29535. }
  29536. if (closePath) {
  29537. vertexData._idx = idx;
  29538. }
  29539. return vertexData;
  29540. };
  29541. /**
  29542. * Creates the VertexData of the Box.
  29543. */
  29544. VertexData.CreateBox = function (options) {
  29545. var normalsSource = [
  29546. new BABYLON.Vector3(0, 0, 1),
  29547. new BABYLON.Vector3(0, 0, -1),
  29548. new BABYLON.Vector3(1, 0, 0),
  29549. new BABYLON.Vector3(-1, 0, 0),
  29550. new BABYLON.Vector3(0, 1, 0),
  29551. new BABYLON.Vector3(0, -1, 0)
  29552. ];
  29553. var indices = [];
  29554. var positions = [];
  29555. var normals = [];
  29556. var uvs = [];
  29557. var width = options.width || options.size || 1;
  29558. var height = options.height || options.size || 1;
  29559. var depth = options.depth || options.size || 1;
  29560. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29561. var faceUV = options.faceUV || new Array(6);
  29562. var faceColors = options.faceColors;
  29563. var colors = [];
  29564. // default face colors and UV if undefined
  29565. for (var f = 0; f < 6; f++) {
  29566. if (faceUV[f] === undefined) {
  29567. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  29568. }
  29569. if (faceColors && faceColors[f] === undefined) {
  29570. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  29571. }
  29572. }
  29573. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  29574. // Create each face in turn.
  29575. for (var index = 0; index < normalsSource.length; index++) {
  29576. var normal = normalsSource[index];
  29577. // Get two vectors perpendicular to the face normal and to each other.
  29578. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  29579. var side2 = BABYLON.Vector3.Cross(normal, side1);
  29580. // Six indices (two triangles) per face.
  29581. var verticesLength = positions.length / 3;
  29582. indices.push(verticesLength);
  29583. indices.push(verticesLength + 1);
  29584. indices.push(verticesLength + 2);
  29585. indices.push(verticesLength);
  29586. indices.push(verticesLength + 2);
  29587. indices.push(verticesLength + 3);
  29588. // Four vertices per face.
  29589. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  29590. positions.push(vertex.x, vertex.y, vertex.z);
  29591. normals.push(normal.x, normal.y, normal.z);
  29592. uvs.push(faceUV[index].z, faceUV[index].w);
  29593. if (faceColors) {
  29594. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  29595. }
  29596. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  29597. positions.push(vertex.x, vertex.y, vertex.z);
  29598. normals.push(normal.x, normal.y, normal.z);
  29599. uvs.push(faceUV[index].x, faceUV[index].w);
  29600. if (faceColors) {
  29601. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  29602. }
  29603. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  29604. positions.push(vertex.x, vertex.y, vertex.z);
  29605. normals.push(normal.x, normal.y, normal.z);
  29606. uvs.push(faceUV[index].x, faceUV[index].y);
  29607. if (faceColors) {
  29608. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  29609. }
  29610. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  29611. positions.push(vertex.x, vertex.y, vertex.z);
  29612. normals.push(normal.x, normal.y, normal.z);
  29613. uvs.push(faceUV[index].z, faceUV[index].y);
  29614. if (faceColors) {
  29615. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  29616. }
  29617. }
  29618. // sides
  29619. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29620. // Result
  29621. var vertexData = new VertexData();
  29622. vertexData.indices = indices;
  29623. vertexData.positions = positions;
  29624. vertexData.normals = normals;
  29625. vertexData.uvs = uvs;
  29626. if (faceColors) {
  29627. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  29628. vertexData.colors = totalColors;
  29629. }
  29630. return vertexData;
  29631. };
  29632. /**
  29633. * Creates the VertexData of the Sphere.
  29634. */
  29635. VertexData.CreateSphere = function (options) {
  29636. var segments = options.segments || 32;
  29637. var diameterX = options.diameterX || options.diameter || 1;
  29638. var diameterY = options.diameterY || options.diameter || 1;
  29639. var diameterZ = options.diameterZ || options.diameter || 1;
  29640. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  29641. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  29642. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29643. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  29644. var totalZRotationSteps = 2 + segments;
  29645. var totalYRotationSteps = 2 * totalZRotationSteps;
  29646. var indices = [];
  29647. var positions = [];
  29648. var normals = [];
  29649. var uvs = [];
  29650. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  29651. var normalizedZ = zRotationStep / totalZRotationSteps;
  29652. var angleZ = normalizedZ * Math.PI * slice;
  29653. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  29654. var normalizedY = yRotationStep / totalYRotationSteps;
  29655. var angleY = normalizedY * Math.PI * 2 * arc;
  29656. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  29657. var rotationY = BABYLON.Matrix.RotationY(angleY);
  29658. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  29659. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  29660. var vertex = complete.multiply(radius);
  29661. var normal = complete.divide(radius).normalize();
  29662. positions.push(vertex.x, vertex.y, vertex.z);
  29663. normals.push(normal.x, normal.y, normal.z);
  29664. uvs.push(normalizedY, normalizedZ);
  29665. }
  29666. if (zRotationStep > 0) {
  29667. var verticesCount = positions.length / 3;
  29668. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  29669. indices.push((firstIndex));
  29670. indices.push((firstIndex + 1));
  29671. indices.push(firstIndex + totalYRotationSteps + 1);
  29672. indices.push((firstIndex + totalYRotationSteps + 1));
  29673. indices.push((firstIndex + 1));
  29674. indices.push((firstIndex + totalYRotationSteps + 2));
  29675. }
  29676. }
  29677. }
  29678. // Sides
  29679. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29680. // Result
  29681. var vertexData = new VertexData();
  29682. vertexData.indices = indices;
  29683. vertexData.positions = positions;
  29684. vertexData.normals = normals;
  29685. vertexData.uvs = uvs;
  29686. return vertexData;
  29687. };
  29688. /**
  29689. * Creates the VertexData of the Cylinder or Cone.
  29690. */
  29691. VertexData.CreateCylinder = function (options) {
  29692. var height = options.height || 2;
  29693. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  29694. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  29695. var tessellation = options.tessellation || 24;
  29696. var subdivisions = options.subdivisions || 1;
  29697. var hasRings = options.hasRings ? true : false;
  29698. var enclose = options.enclose ? true : false;
  29699. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  29700. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29701. var faceUV = options.faceUV || new Array(3);
  29702. var faceColors = options.faceColors;
  29703. // default face colors and UV if undefined
  29704. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  29705. var ringNb = (hasRings) ? subdivisions : 1;
  29706. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  29707. var f;
  29708. for (f = 0; f < surfaceNb; f++) {
  29709. if (faceColors && faceColors[f] === undefined) {
  29710. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  29711. }
  29712. }
  29713. for (f = 0; f < surfaceNb; f++) {
  29714. if (faceUV && faceUV[f] === undefined) {
  29715. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  29716. }
  29717. }
  29718. var indices = new Array();
  29719. var positions = new Array();
  29720. var normals = new Array();
  29721. var uvs = new Array();
  29722. var colors = new Array();
  29723. var angle_step = Math.PI * 2 * arc / tessellation;
  29724. var angle;
  29725. var h;
  29726. var radius;
  29727. var tan = (diameterBottom - diameterTop) / 2 / height;
  29728. var ringVertex = BABYLON.Vector3.Zero();
  29729. var ringNormal = BABYLON.Vector3.Zero();
  29730. var ringFirstVertex = BABYLON.Vector3.Zero();
  29731. var ringFirstNormal = BABYLON.Vector3.Zero();
  29732. var quadNormal = BABYLON.Vector3.Zero();
  29733. var Y = BABYLON.Axis.Y;
  29734. // positions, normals, uvs
  29735. var i;
  29736. var j;
  29737. var r;
  29738. var ringIdx = 1;
  29739. var s = 1; // surface index
  29740. var cs = 0;
  29741. var v = 0;
  29742. for (i = 0; i <= subdivisions; i++) {
  29743. h = i / subdivisions;
  29744. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  29745. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  29746. for (r = 0; r < ringIdx; r++) {
  29747. if (hasRings) {
  29748. s += r;
  29749. }
  29750. if (enclose) {
  29751. s += 2 * r;
  29752. }
  29753. for (j = 0; j <= tessellation; j++) {
  29754. angle = j * angle_step;
  29755. // position
  29756. ringVertex.x = Math.cos(-angle) * radius;
  29757. ringVertex.y = -height / 2 + h * height;
  29758. ringVertex.z = Math.sin(-angle) * radius;
  29759. // normal
  29760. if (diameterTop === 0 && i === subdivisions) {
  29761. // if no top cap, reuse former normals
  29762. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  29763. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  29764. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  29765. }
  29766. else {
  29767. ringNormal.x = ringVertex.x;
  29768. ringNormal.z = ringVertex.z;
  29769. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  29770. ringNormal.normalize();
  29771. }
  29772. // keep first ring vertex values for enclose
  29773. if (j === 0) {
  29774. ringFirstVertex.copyFrom(ringVertex);
  29775. ringFirstNormal.copyFrom(ringNormal);
  29776. }
  29777. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  29778. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  29779. if (hasRings) {
  29780. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  29781. }
  29782. else {
  29783. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  29784. }
  29785. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  29786. if (faceColors) {
  29787. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  29788. }
  29789. }
  29790. // if enclose, add four vertices and their dedicated normals
  29791. if (arc !== 1 && enclose) {
  29792. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  29793. positions.push(0, ringVertex.y, 0);
  29794. positions.push(0, ringVertex.y, 0);
  29795. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  29796. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  29797. quadNormal.normalize();
  29798. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  29799. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  29800. quadNormal.normalize();
  29801. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  29802. if (hasRings) {
  29803. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  29804. }
  29805. else {
  29806. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  29807. }
  29808. uvs.push(faceUV[s + 1].x, v);
  29809. uvs.push(faceUV[s + 1].z, v);
  29810. if (hasRings) {
  29811. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  29812. }
  29813. else {
  29814. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  29815. }
  29816. uvs.push(faceUV[s + 2].x, v);
  29817. uvs.push(faceUV[s + 2].z, v);
  29818. if (faceColors) {
  29819. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  29820. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  29821. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  29822. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  29823. }
  29824. }
  29825. if (cs !== s) {
  29826. cs = s;
  29827. }
  29828. }
  29829. }
  29830. // indices
  29831. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  29832. var s;
  29833. i = 0;
  29834. for (s = 0; s < subdivisions; s++) {
  29835. var i0 = 0;
  29836. var i1 = 0;
  29837. var i2 = 0;
  29838. var i3 = 0;
  29839. for (j = 0; j < tessellation; j++) {
  29840. i0 = i * (e + 1) + j;
  29841. i1 = (i + 1) * (e + 1) + j;
  29842. i2 = i * (e + 1) + (j + 1);
  29843. i3 = (i + 1) * (e + 1) + (j + 1);
  29844. indices.push(i0, i1, i2);
  29845. indices.push(i3, i2, i1);
  29846. }
  29847. if (arc !== 1 && enclose) {
  29848. indices.push(i0 + 2, i1 + 2, i2 + 2);
  29849. indices.push(i3 + 2, i2 + 2, i1 + 2);
  29850. indices.push(i0 + 4, i1 + 4, i2 + 4);
  29851. indices.push(i3 + 4, i2 + 4, i1 + 4);
  29852. }
  29853. i = (hasRings) ? (i + 2) : (i + 1);
  29854. }
  29855. // Caps
  29856. var createCylinderCap = function (isTop) {
  29857. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  29858. if (radius === 0) {
  29859. return;
  29860. }
  29861. // Cap positions, normals & uvs
  29862. var angle;
  29863. var circleVector;
  29864. var i;
  29865. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  29866. var c = null;
  29867. if (faceColors) {
  29868. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  29869. }
  29870. // cap center
  29871. var vbase = positions.length / 3;
  29872. var offset = isTop ? height / 2 : -height / 2;
  29873. var center = new BABYLON.Vector3(0, offset, 0);
  29874. positions.push(center.x, center.y, center.z);
  29875. normals.push(0, isTop ? 1 : -1, 0);
  29876. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  29877. if (c) {
  29878. colors.push(c.r, c.g, c.b, c.a);
  29879. }
  29880. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  29881. for (i = 0; i <= tessellation; i++) {
  29882. angle = Math.PI * 2 * i * arc / tessellation;
  29883. var cos = Math.cos(-angle);
  29884. var sin = Math.sin(-angle);
  29885. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  29886. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  29887. positions.push(circleVector.x, circleVector.y, circleVector.z);
  29888. normals.push(0, isTop ? 1 : -1, 0);
  29889. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  29890. if (c) {
  29891. colors.push(c.r, c.g, c.b, c.a);
  29892. }
  29893. }
  29894. // Cap indices
  29895. for (i = 0; i < tessellation; i++) {
  29896. if (!isTop) {
  29897. indices.push(vbase);
  29898. indices.push(vbase + (i + 1));
  29899. indices.push(vbase + (i + 2));
  29900. }
  29901. else {
  29902. indices.push(vbase);
  29903. indices.push(vbase + (i + 2));
  29904. indices.push(vbase + (i + 1));
  29905. }
  29906. }
  29907. };
  29908. // add caps to geometry
  29909. createCylinderCap(false);
  29910. createCylinderCap(true);
  29911. // Sides
  29912. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29913. var vertexData = new VertexData();
  29914. vertexData.indices = indices;
  29915. vertexData.positions = positions;
  29916. vertexData.normals = normals;
  29917. vertexData.uvs = uvs;
  29918. if (faceColors) {
  29919. vertexData.colors = colors;
  29920. }
  29921. return vertexData;
  29922. };
  29923. /**
  29924. * Creates the VertexData of the Torus.
  29925. */
  29926. VertexData.CreateTorus = function (options) {
  29927. var indices = [];
  29928. var positions = [];
  29929. var normals = [];
  29930. var uvs = [];
  29931. var diameter = options.diameter || 1;
  29932. var thickness = options.thickness || 0.5;
  29933. var tessellation = options.tessellation || 16;
  29934. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  29935. var stride = tessellation + 1;
  29936. for (var i = 0; i <= tessellation; i++) {
  29937. var u = i / tessellation;
  29938. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  29939. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  29940. for (var j = 0; j <= tessellation; j++) {
  29941. var v = 1 - j / tessellation;
  29942. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  29943. var dx = Math.cos(innerAngle);
  29944. var dy = Math.sin(innerAngle);
  29945. // Create a vertex.
  29946. var normal = new BABYLON.Vector3(dx, dy, 0);
  29947. var position = normal.scale(thickness / 2);
  29948. var textureCoordinate = new BABYLON.Vector2(u, v);
  29949. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  29950. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  29951. positions.push(position.x, position.y, position.z);
  29952. normals.push(normal.x, normal.y, normal.z);
  29953. uvs.push(textureCoordinate.x, textureCoordinate.y);
  29954. // And create indices for two triangles.
  29955. var nextI = (i + 1) % stride;
  29956. var nextJ = (j + 1) % stride;
  29957. indices.push(i * stride + j);
  29958. indices.push(i * stride + nextJ);
  29959. indices.push(nextI * stride + j);
  29960. indices.push(i * stride + nextJ);
  29961. indices.push(nextI * stride + nextJ);
  29962. indices.push(nextI * stride + j);
  29963. }
  29964. }
  29965. // Sides
  29966. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  29967. // Result
  29968. var vertexData = new VertexData();
  29969. vertexData.indices = indices;
  29970. vertexData.positions = positions;
  29971. vertexData.normals = normals;
  29972. vertexData.uvs = uvs;
  29973. return vertexData;
  29974. };
  29975. /**
  29976. * Creates the VertexData of the LineSystem.
  29977. */
  29978. VertexData.CreateLineSystem = function (options) {
  29979. var indices = [];
  29980. var positions = [];
  29981. var lines = options.lines;
  29982. var colors = options.colors;
  29983. var vertexColors = [];
  29984. var idx = 0;
  29985. for (var l = 0; l < lines.length; l++) {
  29986. var points = lines[l];
  29987. for (var index = 0; index < points.length; index++) {
  29988. positions.push(points[index].x, points[index].y, points[index].z);
  29989. if (colors) {
  29990. var color = colors[l];
  29991. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  29992. }
  29993. if (index > 0) {
  29994. indices.push(idx - 1);
  29995. indices.push(idx);
  29996. }
  29997. idx++;
  29998. }
  29999. }
  30000. var vertexData = new VertexData();
  30001. vertexData.indices = indices;
  30002. vertexData.positions = positions;
  30003. if (colors) {
  30004. vertexData.colors = vertexColors;
  30005. }
  30006. return vertexData;
  30007. };
  30008. /**
  30009. * Create the VertexData of the DashedLines.
  30010. */
  30011. VertexData.CreateDashedLines = function (options) {
  30012. var dashSize = options.dashSize || 3;
  30013. var gapSize = options.gapSize || 1;
  30014. var dashNb = options.dashNb || 200;
  30015. var points = options.points;
  30016. var positions = new Array();
  30017. var indices = new Array();
  30018. var curvect = BABYLON.Vector3.Zero();
  30019. var lg = 0;
  30020. var nb = 0;
  30021. var shft = 0;
  30022. var dashshft = 0;
  30023. var curshft = 0;
  30024. var idx = 0;
  30025. var i = 0;
  30026. for (i = 0; i < points.length - 1; i++) {
  30027. points[i + 1].subtractToRef(points[i], curvect);
  30028. lg += curvect.length();
  30029. }
  30030. shft = lg / dashNb;
  30031. dashshft = dashSize * shft / (dashSize + gapSize);
  30032. for (i = 0; i < points.length - 1; i++) {
  30033. points[i + 1].subtractToRef(points[i], curvect);
  30034. nb = Math.floor(curvect.length() / shft);
  30035. curvect.normalize();
  30036. for (var j = 0; j < nb; j++) {
  30037. curshft = shft * j;
  30038. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  30039. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  30040. indices.push(idx, idx + 1);
  30041. idx += 2;
  30042. }
  30043. }
  30044. // Result
  30045. var vertexData = new VertexData();
  30046. vertexData.positions = positions;
  30047. vertexData.indices = indices;
  30048. return vertexData;
  30049. };
  30050. /**
  30051. * Creates the VertexData of the Ground.
  30052. */
  30053. VertexData.CreateGround = function (options) {
  30054. var indices = [];
  30055. var positions = [];
  30056. var normals = [];
  30057. var uvs = [];
  30058. var row, col;
  30059. var width = options.width || 1;
  30060. var height = options.height || 1;
  30061. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  30062. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  30063. for (row = 0; row <= subdivisionsY; row++) {
  30064. for (col = 0; col <= subdivisionsX; col++) {
  30065. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  30066. var normal = new BABYLON.Vector3(0, 1.0, 0);
  30067. positions.push(position.x, position.y, position.z);
  30068. normals.push(normal.x, normal.y, normal.z);
  30069. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  30070. }
  30071. }
  30072. for (row = 0; row < subdivisionsY; row++) {
  30073. for (col = 0; col < subdivisionsX; col++) {
  30074. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  30075. indices.push(col + 1 + row * (subdivisionsX + 1));
  30076. indices.push(col + row * (subdivisionsX + 1));
  30077. indices.push(col + (row + 1) * (subdivisionsX + 1));
  30078. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  30079. indices.push(col + row * (subdivisionsX + 1));
  30080. }
  30081. }
  30082. // Result
  30083. var vertexData = new VertexData();
  30084. vertexData.indices = indices;
  30085. vertexData.positions = positions;
  30086. vertexData.normals = normals;
  30087. vertexData.uvs = uvs;
  30088. return vertexData;
  30089. };
  30090. /**
  30091. * Creates the VertexData of the TiledGround.
  30092. */
  30093. VertexData.CreateTiledGround = function (options) {
  30094. var xmin = options.xmin || -1.0;
  30095. var zmin = options.zmin || -1.0;
  30096. var xmax = options.xmax || 1.0;
  30097. var zmax = options.zmax || 1.0;
  30098. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  30099. var precision = options.precision || { w: 1, h: 1 };
  30100. var indices = new Array();
  30101. var positions = new Array();
  30102. var normals = new Array();
  30103. var uvs = new Array();
  30104. var row, col, tileRow, tileCol;
  30105. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  30106. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  30107. precision.w = (precision.w < 1) ? 1 : precision.w;
  30108. precision.h = (precision.h < 1) ? 1 : precision.h;
  30109. var tileSize = {
  30110. 'w': (xmax - xmin) / subdivisions.w,
  30111. 'h': (zmax - zmin) / subdivisions.h
  30112. };
  30113. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  30114. // Indices
  30115. var base = positions.length / 3;
  30116. var rowLength = precision.w + 1;
  30117. for (row = 0; row < precision.h; row++) {
  30118. for (col = 0; col < precision.w; col++) {
  30119. var square = [
  30120. base + col + row * rowLength,
  30121. base + (col + 1) + row * rowLength,
  30122. base + (col + 1) + (row + 1) * rowLength,
  30123. base + col + (row + 1) * rowLength
  30124. ];
  30125. indices.push(square[1]);
  30126. indices.push(square[2]);
  30127. indices.push(square[3]);
  30128. indices.push(square[0]);
  30129. indices.push(square[1]);
  30130. indices.push(square[3]);
  30131. }
  30132. }
  30133. // Position, normals and uvs
  30134. var position = BABYLON.Vector3.Zero();
  30135. var normal = new BABYLON.Vector3(0, 1.0, 0);
  30136. for (row = 0; row <= precision.h; row++) {
  30137. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  30138. for (col = 0; col <= precision.w; col++) {
  30139. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  30140. position.y = 0;
  30141. positions.push(position.x, position.y, position.z);
  30142. normals.push(normal.x, normal.y, normal.z);
  30143. uvs.push(col / precision.w, row / precision.h);
  30144. }
  30145. }
  30146. }
  30147. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  30148. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  30149. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  30150. }
  30151. }
  30152. // Result
  30153. var vertexData = new VertexData();
  30154. vertexData.indices = indices;
  30155. vertexData.positions = positions;
  30156. vertexData.normals = normals;
  30157. vertexData.uvs = uvs;
  30158. return vertexData;
  30159. };
  30160. /**
  30161. * Creates the VertexData of the Ground designed from a heightmap.
  30162. */
  30163. VertexData.CreateGroundFromHeightMap = function (options) {
  30164. var indices = [];
  30165. var positions = [];
  30166. var normals = [];
  30167. var uvs = [];
  30168. var row, col;
  30169. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  30170. // Vertices
  30171. for (row = 0; row <= options.subdivisions; row++) {
  30172. for (col = 0; col <= options.subdivisions; col++) {
  30173. 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));
  30174. // Compute height
  30175. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  30176. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  30177. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  30178. var r = options.buffer[pos] / 255.0;
  30179. var g = options.buffer[pos + 1] / 255.0;
  30180. var b = options.buffer[pos + 2] / 255.0;
  30181. var gradient = r * filter.r + g * filter.g + b * filter.b;
  30182. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  30183. // Add vertex
  30184. positions.push(position.x, position.y, position.z);
  30185. normals.push(0, 0, 0);
  30186. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  30187. }
  30188. }
  30189. // Indices
  30190. for (row = 0; row < options.subdivisions; row++) {
  30191. for (col = 0; col < options.subdivisions; col++) {
  30192. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  30193. indices.push(col + 1 + row * (options.subdivisions + 1));
  30194. indices.push(col + row * (options.subdivisions + 1));
  30195. indices.push(col + (row + 1) * (options.subdivisions + 1));
  30196. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  30197. indices.push(col + row * (options.subdivisions + 1));
  30198. }
  30199. }
  30200. // Normals
  30201. VertexData.ComputeNormals(positions, indices, normals);
  30202. // Result
  30203. var vertexData = new VertexData();
  30204. vertexData.indices = indices;
  30205. vertexData.positions = positions;
  30206. vertexData.normals = normals;
  30207. vertexData.uvs = uvs;
  30208. return vertexData;
  30209. };
  30210. /**
  30211. * Creates the VertexData of the Plane.
  30212. */
  30213. VertexData.CreatePlane = function (options) {
  30214. var indices = [];
  30215. var positions = [];
  30216. var normals = [];
  30217. var uvs = [];
  30218. var width = options.width || options.size || 1;
  30219. var height = options.height || options.size || 1;
  30220. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30221. // Vertices
  30222. var halfWidth = width / 2.0;
  30223. var halfHeight = height / 2.0;
  30224. positions.push(-halfWidth, -halfHeight, 0);
  30225. normals.push(0, 0, -1.0);
  30226. uvs.push(0.0, 0.0);
  30227. positions.push(halfWidth, -halfHeight, 0);
  30228. normals.push(0, 0, -1.0);
  30229. uvs.push(1.0, 0.0);
  30230. positions.push(halfWidth, halfHeight, 0);
  30231. normals.push(0, 0, -1.0);
  30232. uvs.push(1.0, 1.0);
  30233. positions.push(-halfWidth, halfHeight, 0);
  30234. normals.push(0, 0, -1.0);
  30235. uvs.push(0.0, 1.0);
  30236. // Indices
  30237. indices.push(0);
  30238. indices.push(1);
  30239. indices.push(2);
  30240. indices.push(0);
  30241. indices.push(2);
  30242. indices.push(3);
  30243. // Sides
  30244. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30245. // Result
  30246. var vertexData = new VertexData();
  30247. vertexData.indices = indices;
  30248. vertexData.positions = positions;
  30249. vertexData.normals = normals;
  30250. vertexData.uvs = uvs;
  30251. return vertexData;
  30252. };
  30253. /**
  30254. * Creates the VertexData of the Disc or regular Polygon.
  30255. */
  30256. VertexData.CreateDisc = function (options) {
  30257. var positions = new Array();
  30258. var indices = new Array();
  30259. var normals = new Array();
  30260. var uvs = new Array();
  30261. var radius = options.radius || 0.5;
  30262. var tessellation = options.tessellation || 64;
  30263. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  30264. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30265. // positions and uvs
  30266. positions.push(0, 0, 0); // disc center first
  30267. uvs.push(0.5, 0.5);
  30268. var theta = Math.PI * 2 * arc;
  30269. var step = theta / tessellation;
  30270. for (var a = 0; a < theta; a += step) {
  30271. var x = Math.cos(a);
  30272. var y = Math.sin(a);
  30273. var u = (x + 1) / 2;
  30274. var v = (1 - y) / 2;
  30275. positions.push(radius * x, radius * y, 0);
  30276. uvs.push(u, v);
  30277. }
  30278. if (arc === 1) {
  30279. positions.push(positions[3], positions[4], positions[5]); // close the circle
  30280. uvs.push(uvs[2], uvs[3]);
  30281. }
  30282. //indices
  30283. var vertexNb = positions.length / 3;
  30284. for (var i = 1; i < vertexNb - 1; i++) {
  30285. indices.push(i + 1, 0, i);
  30286. }
  30287. // result
  30288. VertexData.ComputeNormals(positions, indices, normals);
  30289. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30290. var vertexData = new VertexData();
  30291. vertexData.indices = indices;
  30292. vertexData.positions = positions;
  30293. vertexData.normals = normals;
  30294. vertexData.uvs = uvs;
  30295. return vertexData;
  30296. };
  30297. /**
  30298. * Re-creates the VertexData of the Polygon for sideOrientation.
  30299. */
  30300. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  30301. var faceUV = fUV || new Array(3);
  30302. var faceColors = fColors;
  30303. var colors = [];
  30304. // default face colors and UV if undefined
  30305. for (var f = 0; f < 3; f++) {
  30306. if (faceUV[f] === undefined) {
  30307. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  30308. }
  30309. if (faceColors && faceColors[f] === undefined) {
  30310. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  30311. }
  30312. }
  30313. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30314. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  30315. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  30316. var indices = polygon.getIndices();
  30317. // set face colours and textures
  30318. var idx = 0;
  30319. var face = 0;
  30320. for (var index = 0; index < normals.length; index += 3) {
  30321. //Edge Face no. 1
  30322. if (Math.abs(normals[index + 1]) < 0.001) {
  30323. face = 1;
  30324. }
  30325. //Top Face no. 0
  30326. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  30327. face = 0;
  30328. }
  30329. //Bottom Face no. 2
  30330. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  30331. face = 2;
  30332. }
  30333. idx = index / 3;
  30334. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  30335. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  30336. if (faceColors) {
  30337. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  30338. }
  30339. }
  30340. // sides
  30341. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  30342. // Result
  30343. var vertexData = new VertexData();
  30344. vertexData.indices = indices;
  30345. vertexData.positions = positions;
  30346. vertexData.normals = normals;
  30347. vertexData.uvs = uvs;
  30348. if (faceColors) {
  30349. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  30350. vertexData.colors = totalColors;
  30351. }
  30352. return vertexData;
  30353. };
  30354. /**
  30355. * Creates the VertexData of the IcoSphere.
  30356. */
  30357. VertexData.CreateIcoSphere = function (options) {
  30358. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30359. var radius = options.radius || 1;
  30360. var flat = (options.flat === undefined) ? true : options.flat;
  30361. var subdivisions = options.subdivisions || 4;
  30362. var radiusX = options.radiusX || radius;
  30363. var radiusY = options.radiusY || radius;
  30364. var radiusZ = options.radiusZ || radius;
  30365. var t = (1 + Math.sqrt(5)) / 2;
  30366. // 12 vertex x,y,z
  30367. var ico_vertices = [
  30368. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  30369. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  30370. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  30371. ];
  30372. // index of 3 vertex makes a face of icopshere
  30373. var ico_indices = [
  30374. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  30375. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  30376. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  30377. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  30378. ];
  30379. // vertex for uv have aliased position, not for UV
  30380. var vertices_unalias_id = [
  30381. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  30382. // vertex alias
  30383. 0,
  30384. 2,
  30385. 3,
  30386. 3,
  30387. 3,
  30388. 4,
  30389. 7,
  30390. 8,
  30391. 9,
  30392. 9,
  30393. 10,
  30394. 11 // 23: B + 12
  30395. ];
  30396. // uv as integer step (not pixels !)
  30397. var ico_vertexuv = [
  30398. 5, 1, 3, 1, 6, 4, 0, 0,
  30399. 5, 3, 4, 2, 2, 2, 4, 0,
  30400. 2, 0, 1, 1, 6, 0, 6, 2,
  30401. // vertex alias (for same vertex on different faces)
  30402. 0, 4,
  30403. 3, 3,
  30404. 4, 4,
  30405. 3, 1,
  30406. 4, 2,
  30407. 4, 4,
  30408. 0, 2,
  30409. 1, 1,
  30410. 2, 2,
  30411. 3, 3,
  30412. 1, 3,
  30413. 2, 4 // 23: B + 12
  30414. ];
  30415. // Vertices[0, 1, ...9, A, B] : position on UV plane
  30416. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  30417. // First island of uv mapping
  30418. // v = 4h 3+ 2
  30419. // v = 3h 9+ 4
  30420. // v = 2h 9+ 5 B
  30421. // v = 1h 9 1 0
  30422. // v = 0h 3 8 7 A
  30423. // u = 0 1 2 3 4 5 6 *a
  30424. // Second island of uv mapping
  30425. // v = 4h 0+ B+ 4+
  30426. // v = 3h A+ 2+
  30427. // v = 2h 7+ 6 3+
  30428. // v = 1h 8+ 3+
  30429. // v = 0h
  30430. // u = 0 1 2 3 4 5 6 *a
  30431. // Face layout on texture UV mapping
  30432. // ============
  30433. // \ 4 /\ 16 / ======
  30434. // \ / \ / /\ 11 /
  30435. // \/ 7 \/ / \ /
  30436. // ======= / 10 \/
  30437. // /\ 17 /\ =======
  30438. // / \ / \ \ 15 /\
  30439. // / 8 \/ 12 \ \ / \
  30440. // ============ \/ 6 \
  30441. // \ 18 /\ ============
  30442. // \ / \ \ 5 /\ 0 /
  30443. // \/ 13 \ \ / \ /
  30444. // ======= \/ 1 \/
  30445. // =============
  30446. // /\ 19 /\ 2 /\
  30447. // / \ / \ / \
  30448. // / 14 \/ 9 \/ 3 \
  30449. // ===================
  30450. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  30451. var ustep = 138 / 1024;
  30452. var vstep = 239 / 1024;
  30453. var uoffset = 60 / 1024;
  30454. var voffset = 26 / 1024;
  30455. // Second island should have margin, not to touch the first island
  30456. // avoid any borderline artefact in pixel rounding
  30457. var island_u_offset = -40 / 1024;
  30458. var island_v_offset = +20 / 1024;
  30459. // face is either island 0 or 1 :
  30460. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  30461. var island = [
  30462. 0, 0, 0, 0, 1,
  30463. 0, 0, 1, 1, 0,
  30464. 0, 0, 1, 1, 0,
  30465. 0, 1, 1, 1, 0 // 15 - 19
  30466. ];
  30467. var indices = new Array();
  30468. var positions = new Array();
  30469. var normals = new Array();
  30470. var uvs = new Array();
  30471. var current_indice = 0;
  30472. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  30473. var face_vertex_pos = new Array(3);
  30474. var face_vertex_uv = new Array(3);
  30475. var v012;
  30476. for (v012 = 0; v012 < 3; v012++) {
  30477. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  30478. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  30479. }
  30480. // create all with normals
  30481. for (var face = 0; face < 20; face++) {
  30482. // 3 vertex per face
  30483. for (v012 = 0; v012 < 3; v012++) {
  30484. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  30485. var v_id = ico_indices[3 * face + v012];
  30486. // vertex have 3D position (x,y,z)
  30487. 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]);
  30488. // Normalize to get normal, then scale to radius
  30489. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  30490. // uv Coordinates from vertex ID
  30491. 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);
  30492. }
  30493. // Subdivide the face (interpolate pos, norm, uv)
  30494. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  30495. // - norm is linear interpolation of vertex corner normal
  30496. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  30497. // - uv is linear interpolation
  30498. //
  30499. // Topology is as below for sub-divide by 2
  30500. // vertex shown as v0,v1,v2
  30501. // interp index is i1 to progress in range [v0,v1[
  30502. // interp index is i2 to progress in range [v0,v2[
  30503. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  30504. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  30505. //
  30506. //
  30507. // i2 v2
  30508. // ^ ^
  30509. // / / \
  30510. // / / \
  30511. // / / \
  30512. // / / (0,1) \
  30513. // / #---------\
  30514. // / / \ (0,0)'/ \
  30515. // / / \ / \
  30516. // / / \ / \
  30517. // / / (0,0) \ / (1,0) \
  30518. // / #---------#---------\
  30519. // v0 v1
  30520. //
  30521. // --------------------> i1
  30522. //
  30523. // interp of (i1,i2):
  30524. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  30525. // along i1 : lerp(x0,x1, i1/(S-i2))
  30526. //
  30527. // centroid of triangle is needed to get help normal computation
  30528. // (c1,c2) are used for centroid location
  30529. var interp_vertex = function (i1, i2, c1, c2) {
  30530. // vertex is interpolated from
  30531. // - face_vertex_pos[0..2]
  30532. // - face_vertex_uv[0..2]
  30533. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  30534. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  30535. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  30536. pos_interp.normalize();
  30537. var vertex_normal;
  30538. if (flat) {
  30539. // in flat mode, recalculate normal as face centroid normal
  30540. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  30541. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  30542. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  30543. }
  30544. else {
  30545. // in smooth mode, recalculate normal from each single vertex position
  30546. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  30547. }
  30548. // Vertex normal need correction due to X,Y,Z radius scaling
  30549. vertex_normal.x /= radiusX;
  30550. vertex_normal.y /= radiusY;
  30551. vertex_normal.z /= radiusZ;
  30552. vertex_normal.normalize();
  30553. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  30554. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  30555. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  30556. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  30557. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  30558. uvs.push(uv_interp.x, uv_interp.y);
  30559. // push each vertex has member of a face
  30560. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  30561. indices.push(current_indice);
  30562. current_indice++;
  30563. };
  30564. for (var i2 = 0; i2 < subdivisions; i2++) {
  30565. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  30566. // face : (i1,i2) for /\ :
  30567. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  30568. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  30569. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  30570. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  30571. if (i1 + i2 + 1 < subdivisions) {
  30572. // face : (i1,i2)' for \/ :
  30573. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  30574. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  30575. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  30576. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  30577. }
  30578. }
  30579. }
  30580. }
  30581. // Sides
  30582. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30583. // Result
  30584. var vertexData = new VertexData();
  30585. vertexData.indices = indices;
  30586. vertexData.positions = positions;
  30587. vertexData.normals = normals;
  30588. vertexData.uvs = uvs;
  30589. return vertexData;
  30590. };
  30591. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  30592. /**
  30593. * Creates the VertexData of the Polyhedron.
  30594. */
  30595. VertexData.CreatePolyhedron = function (options) {
  30596. // provided polyhedron types :
  30597. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  30598. // 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)
  30599. var polyhedra = [];
  30600. 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]] };
  30601. 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]] };
  30602. polyhedra[2] = {
  30603. 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]],
  30604. 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]]
  30605. };
  30606. polyhedra[3] = {
  30607. 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]],
  30608. 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]]
  30609. };
  30610. polyhedra[4] = {
  30611. 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]],
  30612. 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]]
  30613. };
  30614. 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]] };
  30615. 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]] };
  30616. 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]] };
  30617. 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]] };
  30618. 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]] };
  30619. 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]] };
  30620. 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]] };
  30621. 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]] };
  30622. 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]] };
  30623. polyhedra[14] = {
  30624. 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]],
  30625. 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]]
  30626. };
  30627. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  30628. var size = options.size;
  30629. var sizeX = options.sizeX || size || 1;
  30630. var sizeY = options.sizeY || size || 1;
  30631. var sizeZ = options.sizeZ || size || 1;
  30632. var data = options.custom || polyhedra[type];
  30633. var nbfaces = data.face.length;
  30634. var faceUV = options.faceUV || new Array(nbfaces);
  30635. var faceColors = options.faceColors;
  30636. var flat = (options.flat === undefined) ? true : options.flat;
  30637. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30638. var positions = new Array();
  30639. var indices = new Array();
  30640. var normals = new Array();
  30641. var uvs = new Array();
  30642. var colors = new Array();
  30643. var index = 0;
  30644. var faceIdx = 0; // face cursor in the array "indexes"
  30645. var indexes = new Array();
  30646. var i = 0;
  30647. var f = 0;
  30648. var u, v, ang, x, y, tmp;
  30649. // default face colors and UV if undefined
  30650. if (flat) {
  30651. for (f = 0; f < nbfaces; f++) {
  30652. if (faceColors && faceColors[f] === undefined) {
  30653. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  30654. }
  30655. if (faceUV && faceUV[f] === undefined) {
  30656. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  30657. }
  30658. }
  30659. }
  30660. if (!flat) {
  30661. for (i = 0; i < data.vertex.length; i++) {
  30662. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  30663. uvs.push(0, 0);
  30664. }
  30665. for (f = 0; f < nbfaces; f++) {
  30666. for (i = 0; i < data.face[f].length - 2; i++) {
  30667. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  30668. }
  30669. }
  30670. }
  30671. else {
  30672. for (f = 0; f < nbfaces; f++) {
  30673. var fl = data.face[f].length; // number of vertices of the current face
  30674. ang = 2 * Math.PI / fl;
  30675. x = 0.5 * Math.tan(ang / 2);
  30676. y = 0.5;
  30677. // positions, uvs, colors
  30678. for (i = 0; i < fl; i++) {
  30679. // positions
  30680. 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);
  30681. indexes.push(index);
  30682. index++;
  30683. // uvs
  30684. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  30685. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  30686. uvs.push(u, v);
  30687. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  30688. y = x * Math.sin(ang) + y * Math.cos(ang);
  30689. x = tmp;
  30690. // colors
  30691. if (faceColors) {
  30692. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  30693. }
  30694. }
  30695. // indices from indexes
  30696. for (i = 0; i < fl - 2; i++) {
  30697. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  30698. }
  30699. faceIdx += fl;
  30700. }
  30701. }
  30702. VertexData.ComputeNormals(positions, indices, normals);
  30703. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30704. var vertexData = new VertexData();
  30705. vertexData.positions = positions;
  30706. vertexData.indices = indices;
  30707. vertexData.normals = normals;
  30708. vertexData.uvs = uvs;
  30709. if (faceColors && flat) {
  30710. vertexData.colors = colors;
  30711. }
  30712. return vertexData;
  30713. };
  30714. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  30715. /**
  30716. * Creates the VertexData of the Torus Knot.
  30717. */
  30718. VertexData.CreateTorusKnot = function (options) {
  30719. var indices = new Array();
  30720. var positions = new Array();
  30721. var normals = new Array();
  30722. var uvs = new Array();
  30723. var radius = options.radius || 2;
  30724. var tube = options.tube || 0.5;
  30725. var radialSegments = options.radialSegments || 32;
  30726. var tubularSegments = options.tubularSegments || 32;
  30727. var p = options.p || 2;
  30728. var q = options.q || 3;
  30729. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30730. // Helper
  30731. var getPos = function (angle) {
  30732. var cu = Math.cos(angle);
  30733. var su = Math.sin(angle);
  30734. var quOverP = q / p * angle;
  30735. var cs = Math.cos(quOverP);
  30736. var tx = radius * (2 + cs) * 0.5 * cu;
  30737. var ty = radius * (2 + cs) * su * 0.5;
  30738. var tz = radius * Math.sin(quOverP) * 0.5;
  30739. return new BABYLON.Vector3(tx, ty, tz);
  30740. };
  30741. // Vertices
  30742. var i;
  30743. var j;
  30744. for (i = 0; i <= radialSegments; i++) {
  30745. var modI = i % radialSegments;
  30746. var u = modI / radialSegments * 2 * p * Math.PI;
  30747. var p1 = getPos(u);
  30748. var p2 = getPos(u + 0.01);
  30749. var tang = p2.subtract(p1);
  30750. var n = p2.add(p1);
  30751. var bitan = BABYLON.Vector3.Cross(tang, n);
  30752. n = BABYLON.Vector3.Cross(bitan, tang);
  30753. bitan.normalize();
  30754. n.normalize();
  30755. for (j = 0; j < tubularSegments; j++) {
  30756. var modJ = j % tubularSegments;
  30757. var v = modJ / tubularSegments * 2 * Math.PI;
  30758. var cx = -tube * Math.cos(v);
  30759. var cy = tube * Math.sin(v);
  30760. positions.push(p1.x + cx * n.x + cy * bitan.x);
  30761. positions.push(p1.y + cx * n.y + cy * bitan.y);
  30762. positions.push(p1.z + cx * n.z + cy * bitan.z);
  30763. uvs.push(i / radialSegments);
  30764. uvs.push(j / tubularSegments);
  30765. }
  30766. }
  30767. for (i = 0; i < radialSegments; i++) {
  30768. for (j = 0; j < tubularSegments; j++) {
  30769. var jNext = (j + 1) % tubularSegments;
  30770. var a = i * tubularSegments + j;
  30771. var b = (i + 1) * tubularSegments + j;
  30772. var c = (i + 1) * tubularSegments + jNext;
  30773. var d = i * tubularSegments + jNext;
  30774. indices.push(d);
  30775. indices.push(b);
  30776. indices.push(a);
  30777. indices.push(d);
  30778. indices.push(c);
  30779. indices.push(b);
  30780. }
  30781. }
  30782. // Normals
  30783. VertexData.ComputeNormals(positions, indices, normals);
  30784. // Sides
  30785. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  30786. // Result
  30787. var vertexData = new VertexData();
  30788. vertexData.indices = indices;
  30789. vertexData.positions = positions;
  30790. vertexData.normals = normals;
  30791. vertexData.uvs = uvs;
  30792. return vertexData;
  30793. };
  30794. // Tools
  30795. /**
  30796. * @param {any} - positions (number[] or Float32Array)
  30797. * @param {any} - indices (number[] or Uint16Array)
  30798. * @param {any} - normals (number[] or Float32Array)
  30799. * options (optional) :
  30800. * facetPositions : optional array of facet positions (vector3)
  30801. * facetNormals : optional array of facet normals (vector3)
  30802. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  30803. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  30804. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  30805. * bbSize : optional bounding box size data, required for facetPartitioning computation
  30806. * bInfo : optional bounding info, required for facetPartitioning computation
  30807. * useRightHandedSystem: optional boolean to for right handed system computation
  30808. * depthSort : optional boolean to enable the facet depth sort computation
  30809. * distanceTo : optional Vector3 to compute the facet depth from this location
  30810. * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  30811. */
  30812. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  30813. // temporary scalar variables
  30814. var index = 0; // facet index
  30815. var p1p2x = 0.0; // p1p2 vector x coordinate
  30816. var p1p2y = 0.0; // p1p2 vector y coordinate
  30817. var p1p2z = 0.0; // p1p2 vector z coordinate
  30818. var p3p2x = 0.0; // p3p2 vector x coordinate
  30819. var p3p2y = 0.0; // p3p2 vector y coordinate
  30820. var p3p2z = 0.0; // p3p2 vector z coordinate
  30821. var faceNormalx = 0.0; // facet normal x coordinate
  30822. var faceNormaly = 0.0; // facet normal y coordinate
  30823. var faceNormalz = 0.0; // facet normal z coordinate
  30824. var length = 0.0; // facet normal length before normalization
  30825. var v1x = 0; // vector1 x index in the positions array
  30826. var v1y = 0; // vector1 y index in the positions array
  30827. var v1z = 0; // vector1 z index in the positions array
  30828. var v2x = 0; // vector2 x index in the positions array
  30829. var v2y = 0; // vector2 y index in the positions array
  30830. var v2z = 0; // vector2 z index in the positions array
  30831. var v3x = 0; // vector3 x index in the positions array
  30832. var v3y = 0; // vector3 y index in the positions array
  30833. var v3z = 0; // vector3 z index in the positions array
  30834. var computeFacetNormals = false;
  30835. var computeFacetPositions = false;
  30836. var computeFacetPartitioning = false;
  30837. var computeDepthSort = false;
  30838. var faceNormalSign = 1;
  30839. var ratio = 0;
  30840. var distanceTo = null;
  30841. if (options) {
  30842. computeFacetNormals = (options.facetNormals) ? true : false;
  30843. computeFacetPositions = (options.facetPositions) ? true : false;
  30844. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  30845. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  30846. ratio = options.ratio || 0;
  30847. computeDepthSort = (options.depthSort) ? true : false;
  30848. distanceTo = (options.distanceTo);
  30849. if (computeDepthSort) {
  30850. if (distanceTo === undefined) {
  30851. distanceTo = BABYLON.Vector3.Zero();
  30852. }
  30853. var depthSortedFacets = options.depthSortedFacets;
  30854. }
  30855. }
  30856. // facetPartitioning reinit if needed
  30857. var xSubRatio = 0;
  30858. var ySubRatio = 0;
  30859. var zSubRatio = 0;
  30860. var subSq = 0;
  30861. if (computeFacetPartitioning && options && options.bbSize) {
  30862. var ox = 0; // X partitioning index for facet position
  30863. var oy = 0; // Y partinioning index for facet position
  30864. var oz = 0; // Z partinioning index for facet position
  30865. var b1x = 0; // X partitioning index for facet v1 vertex
  30866. var b1y = 0; // Y partitioning index for facet v1 vertex
  30867. var b1z = 0; // z partitioning index for facet v1 vertex
  30868. var b2x = 0; // X partitioning index for facet v2 vertex
  30869. var b2y = 0; // Y partitioning index for facet v2 vertex
  30870. var b2z = 0; // Z partitioning index for facet v2 vertex
  30871. var b3x = 0; // X partitioning index for facet v3 vertex
  30872. var b3y = 0; // Y partitioning index for facet v3 vertex
  30873. var b3z = 0; // Z partitioning index for facet v3 vertex
  30874. var block_idx_o = 0; // facet barycenter block index
  30875. var block_idx_v1 = 0; // v1 vertex block index
  30876. var block_idx_v2 = 0; // v2 vertex block index
  30877. var block_idx_v3 = 0; // v3 vertex block index
  30878. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  30879. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  30880. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  30881. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  30882. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  30883. subSq = options.subDiv.max * options.subDiv.max;
  30884. options.facetPartitioning.length = 0;
  30885. }
  30886. // reset the normals
  30887. for (index = 0; index < positions.length; index++) {
  30888. normals[index] = 0.0;
  30889. }
  30890. // Loop : 1 indice triplet = 1 facet
  30891. var nbFaces = (indices.length / 3) | 0;
  30892. for (index = 0; index < nbFaces; index++) {
  30893. // get the indexes of the coordinates of each vertex of the facet
  30894. v1x = indices[index * 3] * 3;
  30895. v1y = v1x + 1;
  30896. v1z = v1x + 2;
  30897. v2x = indices[index * 3 + 1] * 3;
  30898. v2y = v2x + 1;
  30899. v2z = v2x + 2;
  30900. v3x = indices[index * 3 + 2] * 3;
  30901. v3y = v3x + 1;
  30902. v3z = v3x + 2;
  30903. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  30904. p1p2y = positions[v1y] - positions[v2y];
  30905. p1p2z = positions[v1z] - positions[v2z];
  30906. p3p2x = positions[v3x] - positions[v2x];
  30907. p3p2y = positions[v3y] - positions[v2y];
  30908. p3p2z = positions[v3z] - positions[v2z];
  30909. // compute the face normal with the cross product
  30910. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  30911. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  30912. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  30913. // normalize this normal and store it in the array facetData
  30914. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  30915. length = (length === 0) ? 1.0 : length;
  30916. faceNormalx /= length;
  30917. faceNormaly /= length;
  30918. faceNormalz /= length;
  30919. if (computeFacetNormals && options) {
  30920. options.facetNormals[index].x = faceNormalx;
  30921. options.facetNormals[index].y = faceNormaly;
  30922. options.facetNormals[index].z = faceNormalz;
  30923. }
  30924. if (computeFacetPositions && options) {
  30925. // compute and the facet barycenter coordinates in the array facetPositions
  30926. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  30927. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  30928. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  30929. }
  30930. if (computeFacetPartitioning && options) {
  30931. // store the facet indexes in arrays in the main facetPartitioning array :
  30932. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  30933. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  30934. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  30935. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  30936. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  30937. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  30938. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  30939. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  30940. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  30941. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  30942. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  30943. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  30944. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  30945. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  30946. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  30947. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  30948. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  30949. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  30950. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  30951. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  30952. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  30953. // push each facet index in each block containing the vertex
  30954. options.facetPartitioning[block_idx_v1].push(index);
  30955. if (block_idx_v2 != block_idx_v1) {
  30956. options.facetPartitioning[block_idx_v2].push(index);
  30957. }
  30958. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  30959. options.facetPartitioning[block_idx_v3].push(index);
  30960. }
  30961. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  30962. options.facetPartitioning[block_idx_o].push(index);
  30963. }
  30964. }
  30965. if (computeDepthSort && options && options.facetPositions) {
  30966. var dsf = depthSortedFacets[index];
  30967. dsf.ind = index * 3;
  30968. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  30969. }
  30970. // compute the normals anyway
  30971. normals[v1x] += faceNormalx; // accumulate all the normals per face
  30972. normals[v1y] += faceNormaly;
  30973. normals[v1z] += faceNormalz;
  30974. normals[v2x] += faceNormalx;
  30975. normals[v2y] += faceNormaly;
  30976. normals[v2z] += faceNormalz;
  30977. normals[v3x] += faceNormalx;
  30978. normals[v3y] += faceNormaly;
  30979. normals[v3z] += faceNormalz;
  30980. }
  30981. // last normalization of each normal
  30982. for (index = 0; index < normals.length / 3; index++) {
  30983. faceNormalx = normals[index * 3];
  30984. faceNormaly = normals[index * 3 + 1];
  30985. faceNormalz = normals[index * 3 + 2];
  30986. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  30987. length = (length === 0) ? 1.0 : length;
  30988. faceNormalx /= length;
  30989. faceNormaly /= length;
  30990. faceNormalz /= length;
  30991. normals[index * 3] = faceNormalx;
  30992. normals[index * 3 + 1] = faceNormaly;
  30993. normals[index * 3 + 2] = faceNormalz;
  30994. }
  30995. };
  30996. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  30997. var li = indices.length;
  30998. var ln = normals.length;
  30999. var i;
  31000. var n;
  31001. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31002. switch (sideOrientation) {
  31003. case BABYLON.Mesh.FRONTSIDE:
  31004. // nothing changed
  31005. break;
  31006. case BABYLON.Mesh.BACKSIDE:
  31007. var tmp;
  31008. // indices
  31009. for (i = 0; i < li; i += 3) {
  31010. tmp = indices[i];
  31011. indices[i] = indices[i + 2];
  31012. indices[i + 2] = tmp;
  31013. }
  31014. // normals
  31015. for (n = 0; n < ln; n++) {
  31016. normals[n] = -normals[n];
  31017. }
  31018. break;
  31019. case BABYLON.Mesh.DOUBLESIDE:
  31020. // positions
  31021. var lp = positions.length;
  31022. var l = lp / 3;
  31023. for (var p = 0; p < lp; p++) {
  31024. positions[lp + p] = positions[p];
  31025. }
  31026. // indices
  31027. for (i = 0; i < li; i += 3) {
  31028. indices[i + li] = indices[i + 2] + l;
  31029. indices[i + 1 + li] = indices[i + 1] + l;
  31030. indices[i + 2 + li] = indices[i] + l;
  31031. }
  31032. // normals
  31033. for (n = 0; n < ln; n++) {
  31034. normals[ln + n] = -normals[n];
  31035. }
  31036. // uvs
  31037. var lu = uvs.length;
  31038. var u = 0;
  31039. for (u = 0; u < lu; u++) {
  31040. uvs[u + lu] = uvs[u];
  31041. }
  31042. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  31043. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  31044. u = 0;
  31045. for (i = 0; i < lu / 2; i++) {
  31046. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  31047. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  31048. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  31049. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  31050. u += 2;
  31051. }
  31052. break;
  31053. }
  31054. };
  31055. /**
  31056. * Creates a new VertexData from the imported parameters.
  31057. */
  31058. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  31059. var vertexData = new VertexData();
  31060. // positions
  31061. var positions = parsedVertexData.positions;
  31062. if (positions) {
  31063. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  31064. }
  31065. // normals
  31066. var normals = parsedVertexData.normals;
  31067. if (normals) {
  31068. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  31069. }
  31070. // tangents
  31071. var tangents = parsedVertexData.tangents;
  31072. if (tangents) {
  31073. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  31074. }
  31075. // uvs
  31076. var uvs = parsedVertexData.uvs;
  31077. if (uvs) {
  31078. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  31079. }
  31080. // uv2s
  31081. var uv2s = parsedVertexData.uv2s;
  31082. if (uv2s) {
  31083. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  31084. }
  31085. // uv3s
  31086. var uv3s = parsedVertexData.uv3s;
  31087. if (uv3s) {
  31088. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  31089. }
  31090. // uv4s
  31091. var uv4s = parsedVertexData.uv4s;
  31092. if (uv4s) {
  31093. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  31094. }
  31095. // uv5s
  31096. var uv5s = parsedVertexData.uv5s;
  31097. if (uv5s) {
  31098. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  31099. }
  31100. // uv6s
  31101. var uv6s = parsedVertexData.uv6s;
  31102. if (uv6s) {
  31103. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  31104. }
  31105. // colors
  31106. var colors = parsedVertexData.colors;
  31107. if (colors) {
  31108. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  31109. }
  31110. // matricesIndices
  31111. var matricesIndices = parsedVertexData.matricesIndices;
  31112. if (matricesIndices) {
  31113. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  31114. }
  31115. // matricesWeights
  31116. var matricesWeights = parsedVertexData.matricesWeights;
  31117. if (matricesWeights) {
  31118. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  31119. }
  31120. // indices
  31121. var indices = parsedVertexData.indices;
  31122. if (indices) {
  31123. vertexData.indices = indices;
  31124. }
  31125. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  31126. };
  31127. return VertexData;
  31128. }());
  31129. BABYLON.VertexData = VertexData;
  31130. })(BABYLON || (BABYLON = {}));
  31131. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  31132. var BABYLON;
  31133. (function (BABYLON) {
  31134. var Geometry = /** @class */ (function () {
  31135. function Geometry(id, scene, vertexData, updatable, mesh) {
  31136. if (updatable === void 0) { updatable = false; }
  31137. if (mesh === void 0) { mesh = null; }
  31138. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  31139. this._totalVertices = 0;
  31140. this._isDisposed = false;
  31141. this._indexBufferIsUpdatable = false;
  31142. this.id = id;
  31143. this._engine = scene.getEngine();
  31144. this._meshes = [];
  31145. this._scene = scene;
  31146. //Init vertex buffer cache
  31147. this._vertexBuffers = {};
  31148. this._indices = [];
  31149. this._updatable = updatable;
  31150. // vertexData
  31151. if (vertexData) {
  31152. this.setAllVerticesData(vertexData, updatable);
  31153. }
  31154. else {
  31155. this._totalVertices = 0;
  31156. this._indices = [];
  31157. }
  31158. if (this._engine.getCaps().vertexArrayObject) {
  31159. this._vertexArrayObjects = {};
  31160. }
  31161. // applyToMesh
  31162. if (mesh) {
  31163. if (mesh.getClassName() === "LinesMesh") {
  31164. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  31165. this.updateExtend();
  31166. }
  31167. this.applyToMesh(mesh);
  31168. mesh.computeWorldMatrix(true);
  31169. }
  31170. }
  31171. Object.defineProperty(Geometry.prototype, "boundingBias", {
  31172. /**
  31173. * 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
  31174. * @returns The Bias Vector
  31175. */
  31176. get: function () {
  31177. return this._boundingBias;
  31178. },
  31179. set: function (value) {
  31180. if (this._boundingBias && this._boundingBias.equals(value)) {
  31181. return;
  31182. }
  31183. this._boundingBias = value.clone();
  31184. this.updateBoundingInfo(true, null);
  31185. },
  31186. enumerable: true,
  31187. configurable: true
  31188. });
  31189. Geometry.CreateGeometryForMesh = function (mesh) {
  31190. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  31191. geometry.applyToMesh(mesh);
  31192. return geometry;
  31193. };
  31194. Object.defineProperty(Geometry.prototype, "extend", {
  31195. get: function () {
  31196. return this._extend;
  31197. },
  31198. enumerable: true,
  31199. configurable: true
  31200. });
  31201. Geometry.prototype.getScene = function () {
  31202. return this._scene;
  31203. };
  31204. Geometry.prototype.getEngine = function () {
  31205. return this._engine;
  31206. };
  31207. Geometry.prototype.isReady = function () {
  31208. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  31209. };
  31210. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  31211. get: function () {
  31212. for (var index = 0; index < this._meshes.length; index++) {
  31213. if (!this._meshes[index].doNotSerialize) {
  31214. return false;
  31215. }
  31216. }
  31217. return true;
  31218. },
  31219. enumerable: true,
  31220. configurable: true
  31221. });
  31222. Geometry.prototype._rebuild = function () {
  31223. if (this._vertexArrayObjects) {
  31224. this._vertexArrayObjects = {};
  31225. }
  31226. // Index buffer
  31227. if (this._meshes.length !== 0 && this._indices) {
  31228. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  31229. }
  31230. // Vertex buffers
  31231. for (var key in this._vertexBuffers) {
  31232. var vertexBuffer = this._vertexBuffers[key];
  31233. vertexBuffer._rebuild();
  31234. }
  31235. };
  31236. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  31237. vertexData.applyToGeometry(this, updatable);
  31238. this.notifyUpdate();
  31239. };
  31240. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  31241. if (updatable === void 0) { updatable = false; }
  31242. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  31243. this.setVerticesBuffer(buffer);
  31244. };
  31245. Geometry.prototype.removeVerticesData = function (kind) {
  31246. if (this._vertexBuffers[kind]) {
  31247. this._vertexBuffers[kind].dispose();
  31248. delete this._vertexBuffers[kind];
  31249. }
  31250. };
  31251. Geometry.prototype.setVerticesBuffer = function (buffer) {
  31252. var kind = buffer.getKind();
  31253. if (this._vertexBuffers[kind]) {
  31254. this._vertexBuffers[kind].dispose();
  31255. }
  31256. this._vertexBuffers[kind] = buffer;
  31257. if (kind === BABYLON.VertexBuffer.PositionKind) {
  31258. var data = buffer.getData();
  31259. var stride = buffer.getStrideSize();
  31260. this._totalVertices = data.length / stride;
  31261. this.updateExtend(data, stride);
  31262. this._resetPointsArrayCache();
  31263. var meshes = this._meshes;
  31264. var numOfMeshes = meshes.length;
  31265. for (var index = 0; index < numOfMeshes; index++) {
  31266. var mesh = meshes[index];
  31267. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  31268. mesh._createGlobalSubMesh(false);
  31269. mesh.computeWorldMatrix(true);
  31270. }
  31271. }
  31272. this.notifyUpdate(kind);
  31273. if (this._vertexArrayObjects) {
  31274. this._disposeVertexArrayObjects();
  31275. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  31276. }
  31277. };
  31278. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  31279. var vertexBuffer = this.getVertexBuffer(kind);
  31280. if (!vertexBuffer) {
  31281. return;
  31282. }
  31283. vertexBuffer.updateDirectly(data, offset);
  31284. this.notifyUpdate(kind);
  31285. };
  31286. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  31287. if (updateExtends === void 0) { updateExtends = false; }
  31288. var vertexBuffer = this.getVertexBuffer(kind);
  31289. if (!vertexBuffer) {
  31290. return;
  31291. }
  31292. vertexBuffer.update(data);
  31293. if (kind === BABYLON.VertexBuffer.PositionKind) {
  31294. var stride = vertexBuffer.getStrideSize();
  31295. this._totalVertices = data.length / stride;
  31296. this.updateBoundingInfo(updateExtends, data);
  31297. }
  31298. this.notifyUpdate(kind);
  31299. };
  31300. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  31301. if (updateExtends) {
  31302. this.updateExtend(data);
  31303. }
  31304. var meshes = this._meshes;
  31305. var numOfMeshes = meshes.length;
  31306. this._resetPointsArrayCache();
  31307. for (var index = 0; index < numOfMeshes; index++) {
  31308. var mesh = meshes[index];
  31309. if (updateExtends) {
  31310. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  31311. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  31312. var subMesh = mesh.subMeshes[subIndex];
  31313. subMesh.refreshBoundingInfo();
  31314. }
  31315. }
  31316. }
  31317. };
  31318. Geometry.prototype._bind = function (effect, indexToBind) {
  31319. if (!effect) {
  31320. return;
  31321. }
  31322. if (indexToBind === undefined) {
  31323. indexToBind = this._indexBuffer;
  31324. }
  31325. var vbs = this.getVertexBuffers();
  31326. if (!vbs) {
  31327. return;
  31328. }
  31329. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  31330. this._engine.bindBuffers(vbs, indexToBind, effect);
  31331. return;
  31332. }
  31333. // Using VAO
  31334. if (!this._vertexArrayObjects[effect.key]) {
  31335. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  31336. }
  31337. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  31338. };
  31339. Geometry.prototype.getTotalVertices = function () {
  31340. if (this.isReady() === false) {
  31341. return 0;
  31342. }
  31343. return this._totalVertices;
  31344. };
  31345. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  31346. var vertexBuffer = this.getVertexBuffer(kind);
  31347. if (!vertexBuffer) {
  31348. return null;
  31349. }
  31350. var orig = vertexBuffer.getData();
  31351. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  31352. return orig;
  31353. }
  31354. else {
  31355. var len = orig.length;
  31356. var copy = [];
  31357. for (var i = 0; i < len; i++) {
  31358. copy.push(orig[i]);
  31359. }
  31360. return copy;
  31361. }
  31362. };
  31363. /**
  31364. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  31365. * Possible `kind` values :
  31366. * - BABYLON.VertexBuffer.PositionKind
  31367. * - BABYLON.VertexBuffer.UVKind
  31368. * - BABYLON.VertexBuffer.UV2Kind
  31369. * - BABYLON.VertexBuffer.UV3Kind
  31370. * - BABYLON.VertexBuffer.UV4Kind
  31371. * - BABYLON.VertexBuffer.UV5Kind
  31372. * - BABYLON.VertexBuffer.UV6Kind
  31373. * - BABYLON.VertexBuffer.ColorKind
  31374. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31375. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31376. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31377. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31378. */
  31379. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  31380. var vb = this._vertexBuffers[kind];
  31381. if (!vb) {
  31382. return false;
  31383. }
  31384. return vb.isUpdatable();
  31385. };
  31386. Geometry.prototype.getVertexBuffer = function (kind) {
  31387. if (!this.isReady()) {
  31388. return null;
  31389. }
  31390. return this._vertexBuffers[kind];
  31391. };
  31392. Geometry.prototype.getVertexBuffers = function () {
  31393. if (!this.isReady()) {
  31394. return null;
  31395. }
  31396. return this._vertexBuffers;
  31397. };
  31398. Geometry.prototype.isVerticesDataPresent = function (kind) {
  31399. if (!this._vertexBuffers) {
  31400. if (this._delayInfo) {
  31401. return this._delayInfo.indexOf(kind) !== -1;
  31402. }
  31403. return false;
  31404. }
  31405. return this._vertexBuffers[kind] !== undefined;
  31406. };
  31407. Geometry.prototype.getVerticesDataKinds = function () {
  31408. var result = [];
  31409. var kind;
  31410. if (!this._vertexBuffers && this._delayInfo) {
  31411. for (kind in this._delayInfo) {
  31412. result.push(kind);
  31413. }
  31414. }
  31415. else {
  31416. for (kind in this._vertexBuffers) {
  31417. result.push(kind);
  31418. }
  31419. }
  31420. return result;
  31421. };
  31422. Geometry.prototype.updateIndices = function (indices, offset) {
  31423. if (!this._indexBuffer) {
  31424. return;
  31425. }
  31426. if (!this._indexBufferIsUpdatable) {
  31427. this.setIndices(indices, null, true);
  31428. }
  31429. else {
  31430. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  31431. }
  31432. };
  31433. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  31434. if (totalVertices === void 0) { totalVertices = null; }
  31435. if (updatable === void 0) { updatable = false; }
  31436. if (this._indexBuffer) {
  31437. this._engine._releaseBuffer(this._indexBuffer);
  31438. }
  31439. this._disposeVertexArrayObjects();
  31440. this._indices = indices;
  31441. this._indexBufferIsUpdatable = updatable;
  31442. if (this._meshes.length !== 0 && this._indices) {
  31443. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  31444. }
  31445. if (totalVertices != undefined) {
  31446. this._totalVertices = totalVertices;
  31447. }
  31448. var meshes = this._meshes;
  31449. var numOfMeshes = meshes.length;
  31450. for (var index = 0; index < numOfMeshes; index++) {
  31451. meshes[index]._createGlobalSubMesh(true);
  31452. }
  31453. this.notifyUpdate();
  31454. };
  31455. Geometry.prototype.getTotalIndices = function () {
  31456. if (!this.isReady()) {
  31457. return 0;
  31458. }
  31459. return this._indices.length;
  31460. };
  31461. Geometry.prototype.getIndices = function (copyWhenShared) {
  31462. if (!this.isReady()) {
  31463. return null;
  31464. }
  31465. var orig = this._indices;
  31466. if (!copyWhenShared || this._meshes.length === 1) {
  31467. return orig;
  31468. }
  31469. else {
  31470. var len = orig.length;
  31471. var copy = [];
  31472. for (var i = 0; i < len; i++) {
  31473. copy.push(orig[i]);
  31474. }
  31475. return copy;
  31476. }
  31477. };
  31478. Geometry.prototype.getIndexBuffer = function () {
  31479. if (!this.isReady()) {
  31480. return null;
  31481. }
  31482. return this._indexBuffer;
  31483. };
  31484. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  31485. if (effect === void 0) { effect = null; }
  31486. if (!effect || !this._vertexArrayObjects) {
  31487. return;
  31488. }
  31489. if (this._vertexArrayObjects[effect.key]) {
  31490. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  31491. delete this._vertexArrayObjects[effect.key];
  31492. }
  31493. };
  31494. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  31495. var meshes = this._meshes;
  31496. var index = meshes.indexOf(mesh);
  31497. if (index === -1) {
  31498. return;
  31499. }
  31500. meshes.splice(index, 1);
  31501. mesh._geometry = null;
  31502. if (meshes.length === 0 && shouldDispose) {
  31503. this.dispose();
  31504. }
  31505. };
  31506. Geometry.prototype.applyToMesh = function (mesh) {
  31507. if (mesh._geometry === this) {
  31508. return;
  31509. }
  31510. var previousGeometry = mesh._geometry;
  31511. if (previousGeometry) {
  31512. previousGeometry.releaseForMesh(mesh);
  31513. }
  31514. var meshes = this._meshes;
  31515. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  31516. mesh._geometry = this;
  31517. this._scene.pushGeometry(this);
  31518. meshes.push(mesh);
  31519. if (this.isReady()) {
  31520. this._applyToMesh(mesh);
  31521. }
  31522. else {
  31523. mesh._boundingInfo = this._boundingInfo;
  31524. }
  31525. };
  31526. Geometry.prototype.updateExtend = function (data, stride) {
  31527. if (data === void 0) { data = null; }
  31528. if (!data) {
  31529. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  31530. }
  31531. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  31532. };
  31533. Geometry.prototype._applyToMesh = function (mesh) {
  31534. var numOfMeshes = this._meshes.length;
  31535. // vertexBuffers
  31536. for (var kind in this._vertexBuffers) {
  31537. if (numOfMeshes === 1) {
  31538. this._vertexBuffers[kind].create();
  31539. }
  31540. var buffer = this._vertexBuffers[kind].getBuffer();
  31541. if (buffer)
  31542. buffer.references = numOfMeshes;
  31543. if (kind === BABYLON.VertexBuffer.PositionKind) {
  31544. if (!this._extend) {
  31545. this.updateExtend(this._vertexBuffers[kind].getData());
  31546. }
  31547. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  31548. mesh._createGlobalSubMesh(false);
  31549. //bounding info was just created again, world matrix should be applied again.
  31550. mesh._updateBoundingInfo();
  31551. }
  31552. }
  31553. // indexBuffer
  31554. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  31555. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  31556. }
  31557. if (this._indexBuffer) {
  31558. this._indexBuffer.references = numOfMeshes;
  31559. }
  31560. };
  31561. Geometry.prototype.notifyUpdate = function (kind) {
  31562. if (this.onGeometryUpdated) {
  31563. this.onGeometryUpdated(this, kind);
  31564. }
  31565. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  31566. var mesh = _a[_i];
  31567. mesh._markSubMeshesAsAttributesDirty();
  31568. }
  31569. };
  31570. Geometry.prototype.load = function (scene, onLoaded) {
  31571. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31572. return;
  31573. }
  31574. if (this.isReady()) {
  31575. if (onLoaded) {
  31576. onLoaded();
  31577. }
  31578. return;
  31579. }
  31580. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  31581. this._queueLoad(scene, onLoaded);
  31582. };
  31583. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  31584. var _this = this;
  31585. if (!this.delayLoadingFile) {
  31586. return;
  31587. }
  31588. scene._addPendingData(this);
  31589. scene._loadFile(this.delayLoadingFile, function (data) {
  31590. if (!_this._delayLoadingFunction) {
  31591. return;
  31592. }
  31593. _this._delayLoadingFunction(JSON.parse(data), _this);
  31594. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  31595. _this._delayInfo = [];
  31596. scene._removePendingData(_this);
  31597. var meshes = _this._meshes;
  31598. var numOfMeshes = meshes.length;
  31599. for (var index = 0; index < numOfMeshes; index++) {
  31600. _this._applyToMesh(meshes[index]);
  31601. }
  31602. if (onLoaded) {
  31603. onLoaded();
  31604. }
  31605. }, undefined, true);
  31606. };
  31607. /**
  31608. * Invert the geometry to move from a right handed system to a left handed one.
  31609. */
  31610. Geometry.prototype.toLeftHanded = function () {
  31611. // Flip faces
  31612. var tIndices = this.getIndices(false);
  31613. if (tIndices != null && tIndices.length > 0) {
  31614. for (var i = 0; i < tIndices.length; i += 3) {
  31615. var tTemp = tIndices[i + 0];
  31616. tIndices[i + 0] = tIndices[i + 2];
  31617. tIndices[i + 2] = tTemp;
  31618. }
  31619. this.setIndices(tIndices);
  31620. }
  31621. // Negate position.z
  31622. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  31623. if (tPositions != null && tPositions.length > 0) {
  31624. for (var i = 0; i < tPositions.length; i += 3) {
  31625. tPositions[i + 2] = -tPositions[i + 2];
  31626. }
  31627. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  31628. }
  31629. // Negate normal.z
  31630. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  31631. if (tNormals != null && tNormals.length > 0) {
  31632. for (var i = 0; i < tNormals.length; i += 3) {
  31633. tNormals[i + 2] = -tNormals[i + 2];
  31634. }
  31635. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  31636. }
  31637. };
  31638. // Cache
  31639. Geometry.prototype._resetPointsArrayCache = function () {
  31640. this._positions = null;
  31641. };
  31642. Geometry.prototype._generatePointsArray = function () {
  31643. if (this._positions)
  31644. return true;
  31645. this._positions = [];
  31646. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31647. if (!data) {
  31648. return false;
  31649. }
  31650. for (var index = 0; index < data.length; index += 3) {
  31651. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  31652. }
  31653. return true;
  31654. };
  31655. Geometry.prototype.isDisposed = function () {
  31656. return this._isDisposed;
  31657. };
  31658. Geometry.prototype._disposeVertexArrayObjects = function () {
  31659. if (this._vertexArrayObjects) {
  31660. for (var kind in this._vertexArrayObjects) {
  31661. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  31662. }
  31663. this._vertexArrayObjects = {};
  31664. }
  31665. };
  31666. Geometry.prototype.dispose = function () {
  31667. var meshes = this._meshes;
  31668. var numOfMeshes = meshes.length;
  31669. var index;
  31670. for (index = 0; index < numOfMeshes; index++) {
  31671. this.releaseForMesh(meshes[index]);
  31672. }
  31673. this._meshes = [];
  31674. this._disposeVertexArrayObjects();
  31675. for (var kind in this._vertexBuffers) {
  31676. this._vertexBuffers[kind].dispose();
  31677. }
  31678. this._vertexBuffers = {};
  31679. this._totalVertices = 0;
  31680. if (this._indexBuffer) {
  31681. this._engine._releaseBuffer(this._indexBuffer);
  31682. }
  31683. this._indexBuffer = null;
  31684. this._indices = [];
  31685. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  31686. this.delayLoadingFile = null;
  31687. this._delayLoadingFunction = null;
  31688. this._delayInfo = [];
  31689. this._boundingInfo = null;
  31690. this._scene.removeGeometry(this);
  31691. this._isDisposed = true;
  31692. };
  31693. Geometry.prototype.copy = function (id) {
  31694. var vertexData = new BABYLON.VertexData();
  31695. vertexData.indices = [];
  31696. var indices = this.getIndices();
  31697. if (indices) {
  31698. for (var index = 0; index < indices.length; index++) {
  31699. vertexData.indices.push(indices[index]);
  31700. }
  31701. }
  31702. var updatable = false;
  31703. var stopChecking = false;
  31704. var kind;
  31705. for (kind in this._vertexBuffers) {
  31706. // using slice() to make a copy of the array and not just reference it
  31707. var data = this.getVerticesData(kind);
  31708. if (data instanceof Float32Array) {
  31709. vertexData.set(new Float32Array(data), kind);
  31710. }
  31711. else {
  31712. vertexData.set(data.slice(0), kind);
  31713. }
  31714. if (!stopChecking) {
  31715. var vb = this.getVertexBuffer(kind);
  31716. if (vb) {
  31717. updatable = vb.isUpdatable();
  31718. stopChecking = !updatable;
  31719. }
  31720. }
  31721. }
  31722. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  31723. geometry.delayLoadState = this.delayLoadState;
  31724. geometry.delayLoadingFile = this.delayLoadingFile;
  31725. geometry._delayLoadingFunction = this._delayLoadingFunction;
  31726. for (kind in this._delayInfo) {
  31727. geometry._delayInfo = geometry._delayInfo || [];
  31728. geometry._delayInfo.push(kind);
  31729. }
  31730. // Bounding info
  31731. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  31732. return geometry;
  31733. };
  31734. Geometry.prototype.serialize = function () {
  31735. var serializationObject = {};
  31736. serializationObject.id = this.id;
  31737. serializationObject.updatable = this._updatable;
  31738. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  31739. serializationObject.tags = BABYLON.Tags.GetTags(this);
  31740. }
  31741. return serializationObject;
  31742. };
  31743. Geometry.prototype.toNumberArray = function (origin) {
  31744. if (Array.isArray(origin)) {
  31745. return origin;
  31746. }
  31747. else {
  31748. return Array.prototype.slice.call(origin);
  31749. }
  31750. };
  31751. Geometry.prototype.serializeVerticeData = function () {
  31752. var serializationObject = this.serialize();
  31753. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  31754. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  31755. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  31756. serializationObject.positions._updatable = true;
  31757. }
  31758. }
  31759. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  31760. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  31761. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  31762. serializationObject.normals._updatable = true;
  31763. }
  31764. }
  31765. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  31766. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  31767. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  31768. serializationObject.uvs._updatable = true;
  31769. }
  31770. }
  31771. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  31772. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  31773. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  31774. serializationObject.uv2s._updatable = true;
  31775. }
  31776. }
  31777. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  31778. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  31779. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  31780. serializationObject.uv3s._updatable = true;
  31781. }
  31782. }
  31783. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  31784. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  31785. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  31786. serializationObject.uv4s._updatable = true;
  31787. }
  31788. }
  31789. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  31790. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  31791. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  31792. serializationObject.uv5s._updatable = true;
  31793. }
  31794. }
  31795. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  31796. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  31797. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  31798. serializationObject.uv6s._updatable = true;
  31799. }
  31800. }
  31801. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  31802. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  31803. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  31804. serializationObject.colors._updatable = true;
  31805. }
  31806. }
  31807. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  31808. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  31809. serializationObject.matricesIndices._isExpanded = true;
  31810. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  31811. serializationObject.matricesIndices._updatable = true;
  31812. }
  31813. }
  31814. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  31815. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  31816. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  31817. serializationObject.matricesWeights._updatable = true;
  31818. }
  31819. }
  31820. serializationObject.indices = this.toNumberArray(this.getIndices());
  31821. return serializationObject;
  31822. };
  31823. // Statics
  31824. Geometry.ExtractFromMesh = function (mesh, id) {
  31825. var geometry = mesh._geometry;
  31826. if (!geometry) {
  31827. return null;
  31828. }
  31829. return geometry.copy(id);
  31830. };
  31831. /**
  31832. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  31833. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  31834. * Be aware Math.random() could cause collisions, but:
  31835. * "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"
  31836. */
  31837. Geometry.RandomId = function () {
  31838. return BABYLON.Tools.RandomId();
  31839. };
  31840. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  31841. var scene = mesh.getScene();
  31842. // Geometry
  31843. var geometryId = parsedGeometry.geometryId;
  31844. if (geometryId) {
  31845. var geometry = scene.getGeometryByID(geometryId);
  31846. if (geometry) {
  31847. geometry.applyToMesh(mesh);
  31848. }
  31849. }
  31850. else if (parsedGeometry instanceof ArrayBuffer) {
  31851. var binaryInfo = mesh._binaryInfo;
  31852. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  31853. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  31854. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  31855. }
  31856. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  31857. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  31858. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  31859. }
  31860. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  31861. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  31862. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  31863. }
  31864. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  31865. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  31866. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  31867. }
  31868. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  31869. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  31870. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  31871. }
  31872. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  31873. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  31874. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  31875. }
  31876. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  31877. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  31878. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  31879. }
  31880. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  31881. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  31882. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  31883. }
  31884. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  31885. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  31886. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  31887. }
  31888. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  31889. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  31890. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  31891. }
  31892. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  31893. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  31894. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  31895. }
  31896. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  31897. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  31898. mesh.setIndices(indicesData, null);
  31899. }
  31900. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  31901. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  31902. mesh.subMeshes = [];
  31903. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  31904. var materialIndex = subMeshesData[(i * 5) + 0];
  31905. var verticesStart = subMeshesData[(i * 5) + 1];
  31906. var verticesCount = subMeshesData[(i * 5) + 2];
  31907. var indexStart = subMeshesData[(i * 5) + 3];
  31908. var indexCount = subMeshesData[(i * 5) + 4];
  31909. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  31910. }
  31911. }
  31912. }
  31913. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  31914. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  31915. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  31916. if (parsedGeometry.uvs) {
  31917. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  31918. }
  31919. if (parsedGeometry.uvs2) {
  31920. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  31921. }
  31922. if (parsedGeometry.uvs3) {
  31923. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  31924. }
  31925. if (parsedGeometry.uvs4) {
  31926. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  31927. }
  31928. if (parsedGeometry.uvs5) {
  31929. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  31930. }
  31931. if (parsedGeometry.uvs6) {
  31932. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  31933. }
  31934. if (parsedGeometry.colors) {
  31935. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  31936. }
  31937. if (parsedGeometry.matricesIndices) {
  31938. if (!parsedGeometry.matricesIndices._isExpanded) {
  31939. var floatIndices = [];
  31940. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  31941. var matricesIndex = parsedGeometry.matricesIndices[i];
  31942. floatIndices.push(matricesIndex & 0x000000FF);
  31943. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  31944. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  31945. floatIndices.push(matricesIndex >> 24);
  31946. }
  31947. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  31948. }
  31949. else {
  31950. delete parsedGeometry.matricesIndices._isExpanded;
  31951. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  31952. }
  31953. }
  31954. if (parsedGeometry.matricesIndicesExtra) {
  31955. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  31956. var floatIndices = [];
  31957. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  31958. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  31959. floatIndices.push(matricesIndex & 0x000000FF);
  31960. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  31961. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  31962. floatIndices.push(matricesIndex >> 24);
  31963. }
  31964. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  31965. }
  31966. else {
  31967. delete parsedGeometry.matricesIndices._isExpanded;
  31968. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  31969. }
  31970. }
  31971. if (parsedGeometry.matricesWeights) {
  31972. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  31973. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  31974. }
  31975. if (parsedGeometry.matricesWeightsExtra) {
  31976. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  31977. }
  31978. mesh.setIndices(parsedGeometry.indices, null);
  31979. }
  31980. // SubMeshes
  31981. if (parsedGeometry.subMeshes) {
  31982. mesh.subMeshes = [];
  31983. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  31984. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  31985. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  31986. }
  31987. }
  31988. // Flat shading
  31989. if (mesh._shouldGenerateFlatShading) {
  31990. mesh.convertToFlatShadedMesh();
  31991. delete mesh._shouldGenerateFlatShading;
  31992. }
  31993. // Update
  31994. mesh.computeWorldMatrix(true);
  31995. // Octree
  31996. var sceneOctree = scene.selectionOctree;
  31997. if (sceneOctree !== undefined && sceneOctree !== null) {
  31998. sceneOctree.addMesh(mesh);
  31999. }
  32000. };
  32001. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  32002. var epsilon = 1e-3;
  32003. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  32004. return;
  32005. }
  32006. var noInfluenceBoneIndex = 0.0;
  32007. if (parsedGeometry.skeletonId > -1) {
  32008. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  32009. if (!skeleton) {
  32010. return;
  32011. }
  32012. noInfluenceBoneIndex = skeleton.bones.length;
  32013. }
  32014. else {
  32015. return;
  32016. }
  32017. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32018. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  32019. var matricesWeights = parsedGeometry.matricesWeights;
  32020. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  32021. var influencers = parsedGeometry.numBoneInfluencer;
  32022. var size = matricesWeights.length;
  32023. for (var i = 0; i < size; i += 4) {
  32024. var weight = 0.0;
  32025. var firstZeroWeight = -1;
  32026. for (var j = 0; j < 4; j++) {
  32027. var w = matricesWeights[i + j];
  32028. weight += w;
  32029. if (w < epsilon && firstZeroWeight < 0) {
  32030. firstZeroWeight = j;
  32031. }
  32032. }
  32033. if (matricesWeightsExtra) {
  32034. for (var j = 0; j < 4; j++) {
  32035. var w = matricesWeightsExtra[i + j];
  32036. weight += w;
  32037. if (w < epsilon && firstZeroWeight < 0) {
  32038. firstZeroWeight = j + 4;
  32039. }
  32040. }
  32041. }
  32042. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  32043. firstZeroWeight = influencers - 1;
  32044. }
  32045. if (weight > epsilon) {
  32046. var mweight = 1.0 / weight;
  32047. for (var j = 0; j < 4; j++) {
  32048. matricesWeights[i + j] *= mweight;
  32049. }
  32050. if (matricesWeightsExtra) {
  32051. for (var j = 0; j < 4; j++) {
  32052. matricesWeightsExtra[i + j] *= mweight;
  32053. }
  32054. }
  32055. }
  32056. else {
  32057. if (firstZeroWeight >= 4) {
  32058. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  32059. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  32060. }
  32061. else {
  32062. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  32063. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  32064. }
  32065. }
  32066. }
  32067. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  32068. if (parsedGeometry.matricesWeightsExtra) {
  32069. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  32070. }
  32071. };
  32072. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  32073. if (scene.getGeometryByID(parsedVertexData.id)) {
  32074. return null; // null since geometry could be something else than a box...
  32075. }
  32076. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  32077. if (BABYLON.Tags) {
  32078. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  32079. }
  32080. if (parsedVertexData.delayLoadingFile) {
  32081. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  32082. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  32083. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  32084. geometry._delayInfo = [];
  32085. if (parsedVertexData.hasUVs) {
  32086. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  32087. }
  32088. if (parsedVertexData.hasUVs2) {
  32089. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  32090. }
  32091. if (parsedVertexData.hasUVs3) {
  32092. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  32093. }
  32094. if (parsedVertexData.hasUVs4) {
  32095. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  32096. }
  32097. if (parsedVertexData.hasUVs5) {
  32098. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  32099. }
  32100. if (parsedVertexData.hasUVs6) {
  32101. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  32102. }
  32103. if (parsedVertexData.hasColors) {
  32104. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  32105. }
  32106. if (parsedVertexData.hasMatricesIndices) {
  32107. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  32108. }
  32109. if (parsedVertexData.hasMatricesWeights) {
  32110. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  32111. }
  32112. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  32113. }
  32114. else {
  32115. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  32116. }
  32117. scene.pushGeometry(geometry, true);
  32118. return geometry;
  32119. };
  32120. return Geometry;
  32121. }());
  32122. BABYLON.Geometry = Geometry;
  32123. /////// Primitives //////////////////////////////////////////////
  32124. (function (Geometry) {
  32125. var Primitives;
  32126. (function (Primitives) {
  32127. /// Abstract class
  32128. var _Primitive = /** @class */ (function (_super) {
  32129. __extends(_Primitive, _super);
  32130. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  32131. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  32132. if (mesh === void 0) { mesh = null; }
  32133. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  32134. _this._canBeRegenerated = _canBeRegenerated;
  32135. _this._beingRegenerated = true;
  32136. _this.regenerate();
  32137. _this._beingRegenerated = false;
  32138. return _this;
  32139. }
  32140. _Primitive.prototype.canBeRegenerated = function () {
  32141. return this._canBeRegenerated;
  32142. };
  32143. _Primitive.prototype.regenerate = function () {
  32144. if (!this._canBeRegenerated) {
  32145. return;
  32146. }
  32147. this._beingRegenerated = true;
  32148. this.setAllVerticesData(this._regenerateVertexData(), false);
  32149. this._beingRegenerated = false;
  32150. };
  32151. _Primitive.prototype.asNewGeometry = function (id) {
  32152. return _super.prototype.copy.call(this, id);
  32153. };
  32154. // overrides
  32155. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  32156. if (!this._beingRegenerated) {
  32157. return;
  32158. }
  32159. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  32160. };
  32161. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  32162. if (!this._beingRegenerated) {
  32163. return;
  32164. }
  32165. _super.prototype.setVerticesData.call(this, kind, data, false);
  32166. };
  32167. // to override
  32168. // protected
  32169. _Primitive.prototype._regenerateVertexData = function () {
  32170. throw new Error("Abstract method");
  32171. };
  32172. _Primitive.prototype.copy = function (id) {
  32173. throw new Error("Must be overriden in sub-classes.");
  32174. };
  32175. _Primitive.prototype.serialize = function () {
  32176. var serializationObject = _super.prototype.serialize.call(this);
  32177. serializationObject.canBeRegenerated = this.canBeRegenerated();
  32178. return serializationObject;
  32179. };
  32180. return _Primitive;
  32181. }(Geometry));
  32182. Primitives._Primitive = _Primitive;
  32183. var Ribbon = /** @class */ (function (_super) {
  32184. __extends(Ribbon, _super);
  32185. // Members
  32186. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  32187. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32188. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32189. _this.pathArray = pathArray;
  32190. _this.closeArray = closeArray;
  32191. _this.closePath = closePath;
  32192. _this.offset = offset;
  32193. _this.side = side;
  32194. return _this;
  32195. }
  32196. Ribbon.prototype._regenerateVertexData = function () {
  32197. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  32198. };
  32199. Ribbon.prototype.copy = function (id) {
  32200. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  32201. };
  32202. return Ribbon;
  32203. }(_Primitive));
  32204. Primitives.Ribbon = Ribbon;
  32205. var Box = /** @class */ (function (_super) {
  32206. __extends(Box, _super);
  32207. // Members
  32208. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  32209. if (mesh === void 0) { mesh = null; }
  32210. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32211. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32212. _this.size = size;
  32213. _this.side = side;
  32214. return _this;
  32215. }
  32216. Box.prototype._regenerateVertexData = function () {
  32217. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  32218. };
  32219. Box.prototype.copy = function (id) {
  32220. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  32221. };
  32222. Box.prototype.serialize = function () {
  32223. var serializationObject = _super.prototype.serialize.call(this);
  32224. serializationObject.size = this.size;
  32225. return serializationObject;
  32226. };
  32227. Box.Parse = function (parsedBox, scene) {
  32228. if (scene.getGeometryByID(parsedBox.id)) {
  32229. return null; // null since geometry could be something else than a box...
  32230. }
  32231. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  32232. if (BABYLON.Tags) {
  32233. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  32234. }
  32235. scene.pushGeometry(box, true);
  32236. return box;
  32237. };
  32238. return Box;
  32239. }(_Primitive));
  32240. Primitives.Box = Box;
  32241. var Sphere = /** @class */ (function (_super) {
  32242. __extends(Sphere, _super);
  32243. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  32244. if (mesh === void 0) { mesh = null; }
  32245. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32246. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32247. _this.segments = segments;
  32248. _this.diameter = diameter;
  32249. _this.side = side;
  32250. return _this;
  32251. }
  32252. Sphere.prototype._regenerateVertexData = function () {
  32253. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  32254. };
  32255. Sphere.prototype.copy = function (id) {
  32256. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  32257. };
  32258. Sphere.prototype.serialize = function () {
  32259. var serializationObject = _super.prototype.serialize.call(this);
  32260. serializationObject.segments = this.segments;
  32261. serializationObject.diameter = this.diameter;
  32262. return serializationObject;
  32263. };
  32264. Sphere.Parse = function (parsedSphere, scene) {
  32265. if (scene.getGeometryByID(parsedSphere.id)) {
  32266. return null; // null since geometry could be something else than a sphere...
  32267. }
  32268. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  32269. if (BABYLON.Tags) {
  32270. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  32271. }
  32272. scene.pushGeometry(sphere, true);
  32273. return sphere;
  32274. };
  32275. return Sphere;
  32276. }(_Primitive));
  32277. Primitives.Sphere = Sphere;
  32278. var Disc = /** @class */ (function (_super) {
  32279. __extends(Disc, _super);
  32280. // Members
  32281. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  32282. if (mesh === void 0) { mesh = null; }
  32283. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32284. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32285. _this.radius = radius;
  32286. _this.tessellation = tessellation;
  32287. _this.side = side;
  32288. return _this;
  32289. }
  32290. Disc.prototype._regenerateVertexData = function () {
  32291. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  32292. };
  32293. Disc.prototype.copy = function (id) {
  32294. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  32295. };
  32296. return Disc;
  32297. }(_Primitive));
  32298. Primitives.Disc = Disc;
  32299. var Cylinder = /** @class */ (function (_super) {
  32300. __extends(Cylinder, _super);
  32301. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  32302. if (subdivisions === void 0) { subdivisions = 1; }
  32303. if (mesh === void 0) { mesh = null; }
  32304. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32305. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32306. _this.height = height;
  32307. _this.diameterTop = diameterTop;
  32308. _this.diameterBottom = diameterBottom;
  32309. _this.tessellation = tessellation;
  32310. _this.subdivisions = subdivisions;
  32311. _this.side = side;
  32312. return _this;
  32313. }
  32314. Cylinder.prototype._regenerateVertexData = function () {
  32315. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  32316. };
  32317. Cylinder.prototype.copy = function (id) {
  32318. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  32319. };
  32320. Cylinder.prototype.serialize = function () {
  32321. var serializationObject = _super.prototype.serialize.call(this);
  32322. serializationObject.height = this.height;
  32323. serializationObject.diameterTop = this.diameterTop;
  32324. serializationObject.diameterBottom = this.diameterBottom;
  32325. serializationObject.tessellation = this.tessellation;
  32326. return serializationObject;
  32327. };
  32328. Cylinder.Parse = function (parsedCylinder, scene) {
  32329. if (scene.getGeometryByID(parsedCylinder.id)) {
  32330. return null; // null since geometry could be something else than a cylinder...
  32331. }
  32332. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  32333. if (BABYLON.Tags) {
  32334. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  32335. }
  32336. scene.pushGeometry(cylinder, true);
  32337. return cylinder;
  32338. };
  32339. return Cylinder;
  32340. }(_Primitive));
  32341. Primitives.Cylinder = Cylinder;
  32342. var Torus = /** @class */ (function (_super) {
  32343. __extends(Torus, _super);
  32344. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  32345. if (mesh === void 0) { mesh = null; }
  32346. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32347. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32348. _this.diameter = diameter;
  32349. _this.thickness = thickness;
  32350. _this.tessellation = tessellation;
  32351. _this.side = side;
  32352. return _this;
  32353. }
  32354. Torus.prototype._regenerateVertexData = function () {
  32355. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  32356. };
  32357. Torus.prototype.copy = function (id) {
  32358. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  32359. };
  32360. Torus.prototype.serialize = function () {
  32361. var serializationObject = _super.prototype.serialize.call(this);
  32362. serializationObject.diameter = this.diameter;
  32363. serializationObject.thickness = this.thickness;
  32364. serializationObject.tessellation = this.tessellation;
  32365. return serializationObject;
  32366. };
  32367. Torus.Parse = function (parsedTorus, scene) {
  32368. if (scene.getGeometryByID(parsedTorus.id)) {
  32369. return null; // null since geometry could be something else than a torus...
  32370. }
  32371. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  32372. if (BABYLON.Tags) {
  32373. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  32374. }
  32375. scene.pushGeometry(torus, true);
  32376. return torus;
  32377. };
  32378. return Torus;
  32379. }(_Primitive));
  32380. Primitives.Torus = Torus;
  32381. var Ground = /** @class */ (function (_super) {
  32382. __extends(Ground, _super);
  32383. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  32384. if (mesh === void 0) { mesh = null; }
  32385. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32386. _this.width = width;
  32387. _this.height = height;
  32388. _this.subdivisions = subdivisions;
  32389. return _this;
  32390. }
  32391. Ground.prototype._regenerateVertexData = function () {
  32392. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  32393. };
  32394. Ground.prototype.copy = function (id) {
  32395. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  32396. };
  32397. Ground.prototype.serialize = function () {
  32398. var serializationObject = _super.prototype.serialize.call(this);
  32399. serializationObject.width = this.width;
  32400. serializationObject.height = this.height;
  32401. serializationObject.subdivisions = this.subdivisions;
  32402. return serializationObject;
  32403. };
  32404. Ground.Parse = function (parsedGround, scene) {
  32405. if (scene.getGeometryByID(parsedGround.id)) {
  32406. return null; // null since geometry could be something else than a ground...
  32407. }
  32408. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  32409. if (BABYLON.Tags) {
  32410. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  32411. }
  32412. scene.pushGeometry(ground, true);
  32413. return ground;
  32414. };
  32415. return Ground;
  32416. }(_Primitive));
  32417. Primitives.Ground = Ground;
  32418. var TiledGround = /** @class */ (function (_super) {
  32419. __extends(TiledGround, _super);
  32420. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  32421. if (mesh === void 0) { mesh = null; }
  32422. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32423. _this.xmin = xmin;
  32424. _this.zmin = zmin;
  32425. _this.xmax = xmax;
  32426. _this.zmax = zmax;
  32427. _this.subdivisions = subdivisions;
  32428. _this.precision = precision;
  32429. return _this;
  32430. }
  32431. TiledGround.prototype._regenerateVertexData = function () {
  32432. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  32433. };
  32434. TiledGround.prototype.copy = function (id) {
  32435. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  32436. };
  32437. return TiledGround;
  32438. }(_Primitive));
  32439. Primitives.TiledGround = TiledGround;
  32440. var Plane = /** @class */ (function (_super) {
  32441. __extends(Plane, _super);
  32442. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  32443. if (mesh === void 0) { mesh = null; }
  32444. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32445. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32446. _this.size = size;
  32447. _this.side = side;
  32448. return _this;
  32449. }
  32450. Plane.prototype._regenerateVertexData = function () {
  32451. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  32452. };
  32453. Plane.prototype.copy = function (id) {
  32454. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  32455. };
  32456. Plane.prototype.serialize = function () {
  32457. var serializationObject = _super.prototype.serialize.call(this);
  32458. serializationObject.size = this.size;
  32459. return serializationObject;
  32460. };
  32461. Plane.Parse = function (parsedPlane, scene) {
  32462. if (scene.getGeometryByID(parsedPlane.id)) {
  32463. return null; // null since geometry could be something else than a ground...
  32464. }
  32465. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  32466. if (BABYLON.Tags) {
  32467. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  32468. }
  32469. scene.pushGeometry(plane, true);
  32470. return plane;
  32471. };
  32472. return Plane;
  32473. }(_Primitive));
  32474. Primitives.Plane = Plane;
  32475. var TorusKnot = /** @class */ (function (_super) {
  32476. __extends(TorusKnot, _super);
  32477. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  32478. if (mesh === void 0) { mesh = null; }
  32479. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  32480. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  32481. _this.radius = radius;
  32482. _this.tube = tube;
  32483. _this.radialSegments = radialSegments;
  32484. _this.tubularSegments = tubularSegments;
  32485. _this.p = p;
  32486. _this.q = q;
  32487. _this.side = side;
  32488. return _this;
  32489. }
  32490. TorusKnot.prototype._regenerateVertexData = function () {
  32491. 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 });
  32492. };
  32493. TorusKnot.prototype.copy = function (id) {
  32494. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  32495. };
  32496. TorusKnot.prototype.serialize = function () {
  32497. var serializationObject = _super.prototype.serialize.call(this);
  32498. serializationObject.radius = this.radius;
  32499. serializationObject.tube = this.tube;
  32500. serializationObject.radialSegments = this.radialSegments;
  32501. serializationObject.tubularSegments = this.tubularSegments;
  32502. serializationObject.p = this.p;
  32503. serializationObject.q = this.q;
  32504. return serializationObject;
  32505. };
  32506. ;
  32507. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  32508. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  32509. return null; // null since geometry could be something else than a ground...
  32510. }
  32511. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  32512. if (BABYLON.Tags) {
  32513. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  32514. }
  32515. scene.pushGeometry(torusKnot, true);
  32516. return torusKnot;
  32517. };
  32518. return TorusKnot;
  32519. }(_Primitive));
  32520. Primitives.TorusKnot = TorusKnot;
  32521. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  32522. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  32523. })(BABYLON || (BABYLON = {}));
  32524. //# sourceMappingURL=babylon.geometry.js.map
  32525. var BABYLON;
  32526. (function (BABYLON) {
  32527. var PostProcessManager = /** @class */ (function () {
  32528. function PostProcessManager(scene) {
  32529. this._vertexBuffers = {};
  32530. this._scene = scene;
  32531. }
  32532. PostProcessManager.prototype._prepareBuffers = function () {
  32533. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  32534. return;
  32535. }
  32536. // VBO
  32537. var vertices = [];
  32538. vertices.push(1, 1);
  32539. vertices.push(-1, 1);
  32540. vertices.push(-1, -1);
  32541. vertices.push(1, -1);
  32542. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  32543. this._buildIndexBuffer();
  32544. };
  32545. PostProcessManager.prototype._buildIndexBuffer = function () {
  32546. // Indices
  32547. var indices = [];
  32548. indices.push(0);
  32549. indices.push(1);
  32550. indices.push(2);
  32551. indices.push(0);
  32552. indices.push(2);
  32553. indices.push(3);
  32554. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  32555. };
  32556. PostProcessManager.prototype._rebuild = function () {
  32557. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  32558. if (!vb) {
  32559. return;
  32560. }
  32561. vb._rebuild();
  32562. this._buildIndexBuffer();
  32563. };
  32564. // Methods
  32565. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  32566. if (sourceTexture === void 0) { sourceTexture = null; }
  32567. if (postProcesses === void 0) { postProcesses = null; }
  32568. var camera = this._scene.activeCamera;
  32569. if (!camera) {
  32570. return false;
  32571. }
  32572. var postProcesses = postProcesses || camera._postProcesses;
  32573. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  32574. return false;
  32575. }
  32576. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  32577. return true;
  32578. };
  32579. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  32580. if (targetTexture === void 0) { targetTexture = null; }
  32581. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  32582. var engine = this._scene.getEngine();
  32583. for (var index = 0; index < postProcesses.length; index++) {
  32584. if (index < postProcesses.length - 1) {
  32585. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  32586. }
  32587. else {
  32588. if (targetTexture) {
  32589. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  32590. }
  32591. else {
  32592. engine.restoreDefaultFramebuffer();
  32593. }
  32594. }
  32595. var pp = postProcesses[index];
  32596. var effect = pp.apply();
  32597. if (effect) {
  32598. pp.onBeforeRenderObservable.notifyObservers(effect);
  32599. // VBOs
  32600. this._prepareBuffers();
  32601. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  32602. // Draw order
  32603. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  32604. pp.onAfterRenderObservable.notifyObservers(effect);
  32605. }
  32606. }
  32607. // Restore depth buffer
  32608. engine.setDepthBuffer(true);
  32609. engine.setDepthWrite(true);
  32610. };
  32611. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  32612. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  32613. var camera = this._scene.activeCamera;
  32614. if (!camera) {
  32615. return;
  32616. }
  32617. postProcesses = postProcesses || camera._postProcesses;
  32618. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  32619. return;
  32620. }
  32621. var engine = this._scene.getEngine();
  32622. for (var index = 0, len = postProcesses.length; index < len; index++) {
  32623. if (index < len - 1) {
  32624. postProcesses[index + 1].activate(camera, targetTexture);
  32625. }
  32626. else {
  32627. if (targetTexture) {
  32628. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  32629. }
  32630. else {
  32631. engine.restoreDefaultFramebuffer();
  32632. }
  32633. }
  32634. if (doNotPresent) {
  32635. break;
  32636. }
  32637. var pp = postProcesses[index];
  32638. var effect = pp.apply();
  32639. if (effect) {
  32640. pp.onBeforeRenderObservable.notifyObservers(effect);
  32641. // VBOs
  32642. this._prepareBuffers();
  32643. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  32644. // Draw order
  32645. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  32646. pp.onAfterRenderObservable.notifyObservers(effect);
  32647. }
  32648. }
  32649. // Restore states
  32650. engine.setDepthBuffer(true);
  32651. engine.setDepthWrite(true);
  32652. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  32653. };
  32654. PostProcessManager.prototype.dispose = function () {
  32655. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  32656. if (buffer) {
  32657. buffer.dispose();
  32658. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  32659. }
  32660. if (this._indexBuffer) {
  32661. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  32662. this._indexBuffer = null;
  32663. }
  32664. };
  32665. return PostProcessManager;
  32666. }());
  32667. BABYLON.PostProcessManager = PostProcessManager;
  32668. })(BABYLON || (BABYLON = {}));
  32669. //# sourceMappingURL=babylon.postProcessManager.js.map
  32670. var BABYLON;
  32671. (function (BABYLON) {
  32672. /**
  32673. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  32674. */
  32675. var PerformanceMonitor = /** @class */ (function () {
  32676. /**
  32677. * constructor
  32678. * @param frameSampleSize The number of samples required to saturate the sliding window
  32679. */
  32680. function PerformanceMonitor(frameSampleSize) {
  32681. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  32682. this._enabled = true;
  32683. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  32684. }
  32685. /**
  32686. * Samples current frame
  32687. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  32688. */
  32689. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  32690. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  32691. if (!this._enabled)
  32692. return;
  32693. if (this._lastFrameTimeMs != null) {
  32694. var dt = timeMs - this._lastFrameTimeMs;
  32695. this._rollingFrameTime.add(dt);
  32696. }
  32697. this._lastFrameTimeMs = timeMs;
  32698. };
  32699. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  32700. /**
  32701. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  32702. * @return Average frame time in milliseconds
  32703. */
  32704. get: function () {
  32705. return this._rollingFrameTime.average;
  32706. },
  32707. enumerable: true,
  32708. configurable: true
  32709. });
  32710. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  32711. /**
  32712. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  32713. * @return Frame time variance in milliseconds squared
  32714. */
  32715. get: function () {
  32716. return this._rollingFrameTime.variance;
  32717. },
  32718. enumerable: true,
  32719. configurable: true
  32720. });
  32721. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  32722. /**
  32723. * Returns the frame time of the most recent frame
  32724. * @return Frame time in milliseconds
  32725. */
  32726. get: function () {
  32727. return this._rollingFrameTime.history(0);
  32728. },
  32729. enumerable: true,
  32730. configurable: true
  32731. });
  32732. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  32733. /**
  32734. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  32735. * @return Framerate in frames per second
  32736. */
  32737. get: function () {
  32738. return 1000.0 / this._rollingFrameTime.average;
  32739. },
  32740. enumerable: true,
  32741. configurable: true
  32742. });
  32743. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  32744. /**
  32745. * Returns the average framerate in frames per second using the most recent frame time
  32746. * @return Framerate in frames per second
  32747. */
  32748. get: function () {
  32749. var history = this._rollingFrameTime.history(0);
  32750. if (history === 0) {
  32751. return 0;
  32752. }
  32753. return 1000.0 / history;
  32754. },
  32755. enumerable: true,
  32756. configurable: true
  32757. });
  32758. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  32759. /**
  32760. * Returns true if enough samples have been taken to completely fill the sliding window
  32761. * @return true if saturated
  32762. */
  32763. get: function () {
  32764. return this._rollingFrameTime.isSaturated();
  32765. },
  32766. enumerable: true,
  32767. configurable: true
  32768. });
  32769. /**
  32770. * Enables contributions to the sliding window sample set
  32771. */
  32772. PerformanceMonitor.prototype.enable = function () {
  32773. this._enabled = true;
  32774. };
  32775. /**
  32776. * Disables contributions to the sliding window sample set
  32777. * Samples will not be interpolated over the disabled period
  32778. */
  32779. PerformanceMonitor.prototype.disable = function () {
  32780. this._enabled = false;
  32781. //clear last sample to avoid interpolating over the disabled period when next enabled
  32782. this._lastFrameTimeMs = null;
  32783. };
  32784. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  32785. /**
  32786. * Returns true if sampling is enabled
  32787. * @return true if enabled
  32788. */
  32789. get: function () {
  32790. return this._enabled;
  32791. },
  32792. enumerable: true,
  32793. configurable: true
  32794. });
  32795. /**
  32796. * Resets performance monitor
  32797. */
  32798. PerformanceMonitor.prototype.reset = function () {
  32799. //clear last sample to avoid interpolating over the disabled period when next enabled
  32800. this._lastFrameTimeMs = null;
  32801. //wipe record
  32802. this._rollingFrameTime.reset();
  32803. };
  32804. return PerformanceMonitor;
  32805. }());
  32806. BABYLON.PerformanceMonitor = PerformanceMonitor;
  32807. /**
  32808. * RollingAverage
  32809. *
  32810. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  32811. */
  32812. var RollingAverage = /** @class */ (function () {
  32813. /**
  32814. * constructor
  32815. * @param length The number of samples required to saturate the sliding window
  32816. */
  32817. function RollingAverage(length) {
  32818. this._samples = new Array(length);
  32819. this.reset();
  32820. }
  32821. /**
  32822. * Adds a sample to the sample set
  32823. * @param v The sample value
  32824. */
  32825. RollingAverage.prototype.add = function (v) {
  32826. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  32827. var delta;
  32828. //we need to check if we've already wrapped round
  32829. if (this.isSaturated()) {
  32830. //remove bottom of stack from mean
  32831. var bottomValue = this._samples[this._pos];
  32832. delta = bottomValue - this.average;
  32833. this.average -= delta / (this._sampleCount - 1);
  32834. this._m2 -= delta * (bottomValue - this.average);
  32835. }
  32836. else {
  32837. this._sampleCount++;
  32838. }
  32839. //add new value to mean
  32840. delta = v - this.average;
  32841. this.average += delta / (this._sampleCount);
  32842. this._m2 += delta * (v - this.average);
  32843. //set the new variance
  32844. this.variance = this._m2 / (this._sampleCount - 1);
  32845. this._samples[this._pos] = v;
  32846. this._pos++;
  32847. this._pos %= this._samples.length; //positive wrap around
  32848. };
  32849. /**
  32850. * Returns previously added values or null if outside of history or outside the sliding window domain
  32851. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  32852. * @return Value previously recorded with add() or null if outside of range
  32853. */
  32854. RollingAverage.prototype.history = function (i) {
  32855. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  32856. return 0;
  32857. }
  32858. var i0 = this._wrapPosition(this._pos - 1.0);
  32859. return this._samples[this._wrapPosition(i0 - i)];
  32860. };
  32861. /**
  32862. * Returns true if enough samples have been taken to completely fill the sliding window
  32863. * @return true if sample-set saturated
  32864. */
  32865. RollingAverage.prototype.isSaturated = function () {
  32866. return this._sampleCount >= this._samples.length;
  32867. };
  32868. /**
  32869. * Resets the rolling average (equivalent to 0 samples taken so far)
  32870. */
  32871. RollingAverage.prototype.reset = function () {
  32872. this.average = 0;
  32873. this.variance = 0;
  32874. this._sampleCount = 0;
  32875. this._pos = 0;
  32876. this._m2 = 0;
  32877. };
  32878. /**
  32879. * Wraps a value around the sample range boundaries
  32880. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  32881. * @return Wrapped position in sample range
  32882. */
  32883. RollingAverage.prototype._wrapPosition = function (i) {
  32884. var max = this._samples.length;
  32885. return ((i % max) + max) % max;
  32886. };
  32887. return RollingAverage;
  32888. }());
  32889. BABYLON.RollingAverage = RollingAverage;
  32890. })(BABYLON || (BABYLON = {}));
  32891. //# sourceMappingURL=babylon.performanceMonitor.js.map
  32892. var BABYLON;
  32893. (function (BABYLON) {
  32894. /**
  32895. * This groups together the common properties used for image processing either in direct forward pass
  32896. * or through post processing effect depending on the use of the image processing pipeline in your scene
  32897. * or not.
  32898. */
  32899. var ImageProcessingConfiguration = /** @class */ (function () {
  32900. function ImageProcessingConfiguration() {
  32901. /**
  32902. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  32903. */
  32904. this.colorCurves = new BABYLON.ColorCurves();
  32905. this._colorCurvesEnabled = false;
  32906. this._colorGradingEnabled = false;
  32907. this._colorGradingWithGreenDepth = true;
  32908. this._colorGradingBGR = true;
  32909. this._exposure = 1.0;
  32910. this._toneMappingEnabled = false;
  32911. this._contrast = 1.0;
  32912. /**
  32913. * Vignette stretch size.
  32914. */
  32915. this.vignetteStretch = 0;
  32916. /**
  32917. * Vignette centre X Offset.
  32918. */
  32919. this.vignetteCentreX = 0;
  32920. /**
  32921. * Vignette centre Y Offset.
  32922. */
  32923. this.vignetteCentreY = 0;
  32924. /**
  32925. * Vignette weight or intensity of the vignette effect.
  32926. */
  32927. this.vignetteWeight = 1.5;
  32928. /**
  32929. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  32930. * if vignetteEnabled is set to true.
  32931. */
  32932. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  32933. /**
  32934. * Camera field of view used by the Vignette effect.
  32935. */
  32936. this.vignetteCameraFov = 0.5;
  32937. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  32938. this._vignetteEnabled = false;
  32939. this._applyByPostProcess = false;
  32940. this._isEnabled = true;
  32941. /**
  32942. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  32943. * @type {BABYLON.Observable}
  32944. */
  32945. this.onUpdateParameters = new BABYLON.Observable();
  32946. }
  32947. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  32948. /**
  32949. * Gets wether the color curves effect is enabled.
  32950. */
  32951. get: function () {
  32952. return this._colorCurvesEnabled;
  32953. },
  32954. /**
  32955. * Sets wether the color curves effect is enabled.
  32956. */
  32957. set: function (value) {
  32958. if (this._colorCurvesEnabled === value) {
  32959. return;
  32960. }
  32961. this._colorCurvesEnabled = value;
  32962. this._updateParameters();
  32963. },
  32964. enumerable: true,
  32965. configurable: true
  32966. });
  32967. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  32968. /**
  32969. * Gets wether the color grading effect is enabled.
  32970. */
  32971. get: function () {
  32972. return this._colorGradingEnabled;
  32973. },
  32974. /**
  32975. * Sets wether the color grading effect is enabled.
  32976. */
  32977. set: function (value) {
  32978. if (this._colorGradingEnabled === value) {
  32979. return;
  32980. }
  32981. this._colorGradingEnabled = value;
  32982. this._updateParameters();
  32983. },
  32984. enumerable: true,
  32985. configurable: true
  32986. });
  32987. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  32988. /**
  32989. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  32990. */
  32991. get: function () {
  32992. return this._colorGradingWithGreenDepth;
  32993. },
  32994. /**
  32995. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  32996. */
  32997. set: function (value) {
  32998. if (this._colorGradingWithGreenDepth === value) {
  32999. return;
  33000. }
  33001. this._colorGradingWithGreenDepth = value;
  33002. this._updateParameters();
  33003. },
  33004. enumerable: true,
  33005. configurable: true
  33006. });
  33007. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  33008. /**
  33009. * Gets wether the color grading texture contains BGR values.
  33010. */
  33011. get: function () {
  33012. return this._colorGradingBGR;
  33013. },
  33014. /**
  33015. * Sets wether the color grading texture contains BGR values.
  33016. */
  33017. set: function (value) {
  33018. if (this._colorGradingBGR === value) {
  33019. return;
  33020. }
  33021. this._colorGradingBGR = value;
  33022. this._updateParameters();
  33023. },
  33024. enumerable: true,
  33025. configurable: true
  33026. });
  33027. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  33028. /**
  33029. * Gets the Exposure used in the effect.
  33030. */
  33031. get: function () {
  33032. return this._exposure;
  33033. },
  33034. /**
  33035. * Sets the Exposure used in the effect.
  33036. */
  33037. set: function (value) {
  33038. if (this._exposure === value) {
  33039. return;
  33040. }
  33041. this._exposure = value;
  33042. this._updateParameters();
  33043. },
  33044. enumerable: true,
  33045. configurable: true
  33046. });
  33047. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  33048. /**
  33049. * Gets wether the tone mapping effect is enabled.
  33050. */
  33051. get: function () {
  33052. return this._toneMappingEnabled;
  33053. },
  33054. /**
  33055. * Sets wether the tone mapping effect is enabled.
  33056. */
  33057. set: function (value) {
  33058. if (this._toneMappingEnabled === value) {
  33059. return;
  33060. }
  33061. this._toneMappingEnabled = value;
  33062. this._updateParameters();
  33063. },
  33064. enumerable: true,
  33065. configurable: true
  33066. });
  33067. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  33068. /**
  33069. * Gets the contrast used in the effect.
  33070. */
  33071. get: function () {
  33072. return this._contrast;
  33073. },
  33074. /**
  33075. * Sets the contrast used in the effect.
  33076. */
  33077. set: function (value) {
  33078. if (this._contrast === value) {
  33079. return;
  33080. }
  33081. this._contrast = value;
  33082. this._updateParameters();
  33083. },
  33084. enumerable: true,
  33085. configurable: true
  33086. });
  33087. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  33088. /**
  33089. * Gets the vignette blend mode allowing different kind of effect.
  33090. */
  33091. get: function () {
  33092. return this._vignetteBlendMode;
  33093. },
  33094. /**
  33095. * Sets the vignette blend mode allowing different kind of effect.
  33096. */
  33097. set: function (value) {
  33098. if (this._vignetteBlendMode === value) {
  33099. return;
  33100. }
  33101. this._vignetteBlendMode = value;
  33102. this._updateParameters();
  33103. },
  33104. enumerable: true,
  33105. configurable: true
  33106. });
  33107. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  33108. /**
  33109. * Gets wether the vignette effect is enabled.
  33110. */
  33111. get: function () {
  33112. return this._vignetteEnabled;
  33113. },
  33114. /**
  33115. * Sets wether the vignette effect is enabled.
  33116. */
  33117. set: function (value) {
  33118. if (this._vignetteEnabled === value) {
  33119. return;
  33120. }
  33121. this._vignetteEnabled = value;
  33122. this._updateParameters();
  33123. },
  33124. enumerable: true,
  33125. configurable: true
  33126. });
  33127. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  33128. /**
  33129. * Gets wether the image processing is applied through a post process or not.
  33130. */
  33131. get: function () {
  33132. return this._applyByPostProcess;
  33133. },
  33134. /**
  33135. * Sets wether the image processing is applied through a post process or not.
  33136. */
  33137. set: function (value) {
  33138. if (this._applyByPostProcess === value) {
  33139. return;
  33140. }
  33141. this._applyByPostProcess = value;
  33142. this._updateParameters();
  33143. },
  33144. enumerable: true,
  33145. configurable: true
  33146. });
  33147. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  33148. /**
  33149. * Gets wether the image processing is enabled or not.
  33150. */
  33151. get: function () {
  33152. return this._isEnabled;
  33153. },
  33154. /**
  33155. * Sets wether the image processing is enabled or not.
  33156. */
  33157. set: function (value) {
  33158. if (this._isEnabled === value) {
  33159. return;
  33160. }
  33161. this._isEnabled = value;
  33162. this._updateParameters();
  33163. },
  33164. enumerable: true,
  33165. configurable: true
  33166. });
  33167. /**
  33168. * Method called each time the image processing information changes requires to recompile the effect.
  33169. */
  33170. ImageProcessingConfiguration.prototype._updateParameters = function () {
  33171. this.onUpdateParameters.notifyObservers(this);
  33172. };
  33173. ImageProcessingConfiguration.prototype.getClassName = function () {
  33174. return "ImageProcessingConfiguration";
  33175. };
  33176. /**
  33177. * Prepare the list of uniforms associated with the Image Processing effects.
  33178. * @param uniformsList The list of uniforms used in the effect
  33179. * @param defines the list of defines currently in use
  33180. */
  33181. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  33182. if (defines.EXPOSURE) {
  33183. uniforms.push("exposureLinear");
  33184. }
  33185. if (defines.CONTRAST) {
  33186. uniforms.push("contrast");
  33187. }
  33188. if (defines.COLORGRADING) {
  33189. uniforms.push("colorTransformSettings");
  33190. }
  33191. if (defines.VIGNETTE) {
  33192. uniforms.push("vInverseScreenSize");
  33193. uniforms.push("vignetteSettings1");
  33194. uniforms.push("vignetteSettings2");
  33195. }
  33196. if (defines.COLORCURVES) {
  33197. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  33198. }
  33199. };
  33200. /**
  33201. * Prepare the list of samplers associated with the Image Processing effects.
  33202. * @param uniformsList The list of uniforms used in the effect
  33203. * @param defines the list of defines currently in use
  33204. */
  33205. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  33206. if (defines.COLORGRADING) {
  33207. samplersList.push("txColorTransform");
  33208. }
  33209. };
  33210. /**
  33211. * Prepare the list of defines associated to the shader.
  33212. * @param defines the list of defines to complete
  33213. */
  33214. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  33215. if (forPostProcess === void 0) { forPostProcess = false; }
  33216. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  33217. defines.VIGNETTE = false;
  33218. defines.TONEMAPPING = false;
  33219. defines.CONTRAST = false;
  33220. defines.EXPOSURE = false;
  33221. defines.COLORCURVES = false;
  33222. defines.COLORGRADING = false;
  33223. defines.COLORGRADING3D = false;
  33224. defines.IMAGEPROCESSING = false;
  33225. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  33226. return;
  33227. }
  33228. defines.VIGNETTE = this.vignetteEnabled;
  33229. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  33230. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  33231. defines.TONEMAPPING = this.toneMappingEnabled;
  33232. defines.CONTRAST = (this.contrast !== 1.0);
  33233. defines.EXPOSURE = (this.exposure !== 1.0);
  33234. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  33235. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  33236. if (defines.COLORGRADING) {
  33237. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  33238. }
  33239. else {
  33240. defines.COLORGRADING3D = false;
  33241. }
  33242. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  33243. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  33244. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  33245. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  33246. };
  33247. /**
  33248. * Returns true if all the image processing information are ready.
  33249. */
  33250. ImageProcessingConfiguration.prototype.isReady = function () {
  33251. // Color Grading texure can not be none blocking.
  33252. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  33253. };
  33254. /**
  33255. * Binds the image processing to the shader.
  33256. * @param effect The effect to bind to
  33257. */
  33258. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  33259. if (aspectRatio === void 0) { aspectRatio = 1; }
  33260. // Color Curves
  33261. if (this._colorCurvesEnabled && this.colorCurves) {
  33262. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  33263. }
  33264. // Vignette
  33265. if (this._vignetteEnabled) {
  33266. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  33267. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  33268. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  33269. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  33270. var vignetteScaleX = vignetteScaleY * aspectRatio;
  33271. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  33272. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  33273. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  33274. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  33275. var vignettePower = -2.0 * this.vignetteWeight;
  33276. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  33277. }
  33278. // Exposure
  33279. effect.setFloat("exposureLinear", this.exposure);
  33280. // Contrast
  33281. effect.setFloat("contrast", this.contrast);
  33282. // Color transform settings
  33283. if (this.colorGradingTexture) {
  33284. effect.setTexture("txColorTransform", this.colorGradingTexture);
  33285. var textureSize = this.colorGradingTexture.getSize().height;
  33286. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  33287. 0.5 / textureSize, // textureOffset
  33288. textureSize, // textureSize
  33289. this.colorGradingTexture.level // weight
  33290. );
  33291. }
  33292. };
  33293. /**
  33294. * Clones the current image processing instance.
  33295. * @return The cloned image processing
  33296. */
  33297. ImageProcessingConfiguration.prototype.clone = function () {
  33298. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  33299. };
  33300. /**
  33301. * Serializes the current image processing instance to a json representation.
  33302. * @return a JSON representation
  33303. */
  33304. ImageProcessingConfiguration.prototype.serialize = function () {
  33305. return BABYLON.SerializationHelper.Serialize(this);
  33306. };
  33307. /**
  33308. * Parses the image processing from a json representation.
  33309. * @param source the JSON source to parse
  33310. * @return The parsed image processing
  33311. */
  33312. ImageProcessingConfiguration.Parse = function (source) {
  33313. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  33314. };
  33315. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  33316. /**
  33317. * Used to apply the vignette as a mix with the pixel color.
  33318. */
  33319. get: function () {
  33320. return this._VIGNETTEMODE_MULTIPLY;
  33321. },
  33322. enumerable: true,
  33323. configurable: true
  33324. });
  33325. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  33326. /**
  33327. * Used to apply the vignette as a replacement of the pixel color.
  33328. */
  33329. get: function () {
  33330. return this._VIGNETTEMODE_OPAQUE;
  33331. },
  33332. enumerable: true,
  33333. configurable: true
  33334. });
  33335. // Static constants associated to the image processing.
  33336. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  33337. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  33338. __decorate([
  33339. BABYLON.serializeAsColorCurves()
  33340. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  33341. __decorate([
  33342. BABYLON.serialize()
  33343. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  33344. __decorate([
  33345. BABYLON.serializeAsTexture()
  33346. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  33347. __decorate([
  33348. BABYLON.serialize()
  33349. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  33350. __decorate([
  33351. BABYLON.serialize()
  33352. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  33353. __decorate([
  33354. BABYLON.serialize()
  33355. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  33356. __decorate([
  33357. BABYLON.serialize()
  33358. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  33359. __decorate([
  33360. BABYLON.serialize()
  33361. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  33362. __decorate([
  33363. BABYLON.serialize()
  33364. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  33365. __decorate([
  33366. BABYLON.serialize()
  33367. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  33368. __decorate([
  33369. BABYLON.serialize()
  33370. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  33371. __decorate([
  33372. BABYLON.serialize()
  33373. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  33374. __decorate([
  33375. BABYLON.serialize()
  33376. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  33377. __decorate([
  33378. BABYLON.serializeAsColor4()
  33379. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  33380. __decorate([
  33381. BABYLON.serialize()
  33382. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  33383. __decorate([
  33384. BABYLON.serialize()
  33385. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  33386. __decorate([
  33387. BABYLON.serialize()
  33388. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  33389. __decorate([
  33390. BABYLON.serialize()
  33391. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  33392. __decorate([
  33393. BABYLON.serialize()
  33394. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  33395. return ImageProcessingConfiguration;
  33396. }());
  33397. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  33398. })(BABYLON || (BABYLON = {}));
  33399. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  33400. var BABYLON;
  33401. (function (BABYLON) {
  33402. /**
  33403. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  33404. * It can help converting any input color in a desired output one. This can then be used to create effects
  33405. * from sepia, black and white to sixties or futuristic rendering...
  33406. *
  33407. * The only supported format is currently 3dl.
  33408. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  33409. */
  33410. var ColorGradingTexture = /** @class */ (function (_super) {
  33411. __extends(ColorGradingTexture, _super);
  33412. /**
  33413. * Instantiates a ColorGradingTexture from the following parameters.
  33414. *
  33415. * @param url The location of the color gradind data (currently only supporting 3dl)
  33416. * @param scene The scene the texture will be used in
  33417. */
  33418. function ColorGradingTexture(url, scene) {
  33419. var _this = _super.call(this, scene) || this;
  33420. if (!url) {
  33421. return _this;
  33422. }
  33423. _this._engine = scene.getEngine();
  33424. _this._textureMatrix = BABYLON.Matrix.Identity();
  33425. _this.name = url;
  33426. _this.url = url;
  33427. _this.hasAlpha = false;
  33428. _this.isCube = false;
  33429. _this.is3D = _this._engine.webGLVersion > 1;
  33430. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33431. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33432. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  33433. _this.anisotropicFilteringLevel = 1;
  33434. _this._texture = _this._getFromCache(url, true);
  33435. if (!_this._texture) {
  33436. if (!scene.useDelayedTextureLoading) {
  33437. _this.loadTexture();
  33438. }
  33439. else {
  33440. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  33441. }
  33442. }
  33443. return _this;
  33444. }
  33445. /**
  33446. * Returns the texture matrix used in most of the material.
  33447. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  33448. */
  33449. ColorGradingTexture.prototype.getTextureMatrix = function () {
  33450. return this._textureMatrix;
  33451. };
  33452. /**
  33453. * Occurs when the file being loaded is a .3dl LUT file.
  33454. */
  33455. ColorGradingTexture.prototype.load3dlTexture = function () {
  33456. var engine = this._engine;
  33457. var texture;
  33458. if (engine.webGLVersion === 1) {
  33459. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  33460. }
  33461. else {
  33462. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  33463. }
  33464. this._texture = texture;
  33465. var callback = function (text) {
  33466. if (typeof text !== "string") {
  33467. return;
  33468. }
  33469. var data = null;
  33470. var tempData = null;
  33471. var line;
  33472. var lines = text.split('\n');
  33473. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  33474. var maxColor = 0;
  33475. for (var i = 0; i < lines.length; i++) {
  33476. line = lines[i];
  33477. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  33478. continue;
  33479. if (line.indexOf('#') === 0)
  33480. continue;
  33481. var words = line.split(" ");
  33482. if (size === 0) {
  33483. // Number of space + one
  33484. size = words.length;
  33485. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  33486. tempData = new Float32Array(size * size * size * 4);
  33487. continue;
  33488. }
  33489. if (size != 0) {
  33490. var r = Math.max(parseInt(words[0]), 0);
  33491. var g = Math.max(parseInt(words[1]), 0);
  33492. var b = Math.max(parseInt(words[2]), 0);
  33493. maxColor = Math.max(r, maxColor);
  33494. maxColor = Math.max(g, maxColor);
  33495. maxColor = Math.max(b, maxColor);
  33496. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  33497. if (tempData) {
  33498. tempData[pixelStorageIndex + 0] = r;
  33499. tempData[pixelStorageIndex + 1] = g;
  33500. tempData[pixelStorageIndex + 2] = b;
  33501. }
  33502. pixelIndexSlice++;
  33503. if (pixelIndexSlice % size == 0) {
  33504. pixelIndexH++;
  33505. pixelIndexSlice = 0;
  33506. if (pixelIndexH % size == 0) {
  33507. pixelIndexW++;
  33508. pixelIndexH = 0;
  33509. }
  33510. }
  33511. }
  33512. }
  33513. if (tempData && data) {
  33514. for (var i = 0; i < tempData.length; i++) {
  33515. if (i > 0 && (i + 1) % 4 === 0) {
  33516. data[i] = 255;
  33517. }
  33518. else {
  33519. var value = tempData[i];
  33520. data[i] = (value / maxColor * 255);
  33521. }
  33522. }
  33523. }
  33524. if (texture.is3D) {
  33525. texture.updateSize(size, size, size);
  33526. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  33527. }
  33528. else {
  33529. texture.updateSize(size * size, size);
  33530. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  33531. }
  33532. };
  33533. var scene = this.getScene();
  33534. if (scene) {
  33535. scene._loadFile(this.url, callback);
  33536. }
  33537. else {
  33538. this._engine._loadFile(this.url, callback);
  33539. }
  33540. return this._texture;
  33541. };
  33542. /**
  33543. * Starts the loading process of the texture.
  33544. */
  33545. ColorGradingTexture.prototype.loadTexture = function () {
  33546. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  33547. this.load3dlTexture();
  33548. }
  33549. };
  33550. /**
  33551. * Clones the color gradind texture.
  33552. */
  33553. ColorGradingTexture.prototype.clone = function () {
  33554. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  33555. // Base texture
  33556. newTexture.level = this.level;
  33557. return newTexture;
  33558. };
  33559. /**
  33560. * Called during delayed load for textures.
  33561. */
  33562. ColorGradingTexture.prototype.delayLoad = function () {
  33563. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  33564. return;
  33565. }
  33566. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  33567. this._texture = this._getFromCache(this.url, true);
  33568. if (!this._texture) {
  33569. this.loadTexture();
  33570. }
  33571. };
  33572. /**
  33573. * Parses a color grading texture serialized by Babylon.
  33574. * @param parsedTexture The texture information being parsedTexture
  33575. * @param scene The scene to load the texture in
  33576. * @param rootUrl The root url of the data assets to load
  33577. * @return A color gradind texture
  33578. */
  33579. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  33580. var texture = null;
  33581. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  33582. texture = new ColorGradingTexture(parsedTexture.name, scene);
  33583. texture.name = parsedTexture.name;
  33584. texture.level = parsedTexture.level;
  33585. }
  33586. return texture;
  33587. };
  33588. /**
  33589. * Serializes the LUT texture to json format.
  33590. */
  33591. ColorGradingTexture.prototype.serialize = function () {
  33592. if (!this.name) {
  33593. return null;
  33594. }
  33595. var serializationObject = {};
  33596. serializationObject.name = this.name;
  33597. serializationObject.level = this.level;
  33598. serializationObject.customType = "BABYLON.ColorGradingTexture";
  33599. return serializationObject;
  33600. };
  33601. /**
  33602. * Empty line regex stored for GC.
  33603. */
  33604. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  33605. return ColorGradingTexture;
  33606. }(BABYLON.BaseTexture));
  33607. BABYLON.ColorGradingTexture = ColorGradingTexture;
  33608. })(BABYLON || (BABYLON = {}));
  33609. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  33610. var BABYLON;
  33611. (function (BABYLON) {
  33612. /**
  33613. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  33614. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  33615. * 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;
  33616. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  33617. */
  33618. var ColorCurves = /** @class */ (function () {
  33619. function ColorCurves() {
  33620. this._dirty = true;
  33621. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  33622. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  33623. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  33624. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  33625. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  33626. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  33627. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  33628. this._globalHue = 30;
  33629. this._globalDensity = 0;
  33630. this._globalSaturation = 0;
  33631. this._globalExposure = 0;
  33632. this._highlightsHue = 30;
  33633. this._highlightsDensity = 0;
  33634. this._highlightsSaturation = 0;
  33635. this._highlightsExposure = 0;
  33636. this._midtonesHue = 30;
  33637. this._midtonesDensity = 0;
  33638. this._midtonesSaturation = 0;
  33639. this._midtonesExposure = 0;
  33640. this._shadowsHue = 30;
  33641. this._shadowsDensity = 0;
  33642. this._shadowsSaturation = 0;
  33643. this._shadowsExposure = 0;
  33644. }
  33645. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  33646. /**
  33647. * Gets the global Hue value.
  33648. * 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).
  33649. */
  33650. get: function () {
  33651. return this._globalHue;
  33652. },
  33653. /**
  33654. * Sets the global Hue value.
  33655. * 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).
  33656. */
  33657. set: function (value) {
  33658. this._globalHue = value;
  33659. this._dirty = true;
  33660. },
  33661. enumerable: true,
  33662. configurable: true
  33663. });
  33664. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  33665. /**
  33666. * Gets the global Density value.
  33667. * 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.
  33668. * Values less than zero provide a filter of opposite hue.
  33669. */
  33670. get: function () {
  33671. return this._globalDensity;
  33672. },
  33673. /**
  33674. * Sets the global Density value.
  33675. * 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.
  33676. * Values less than zero provide a filter of opposite hue.
  33677. */
  33678. set: function (value) {
  33679. this._globalDensity = value;
  33680. this._dirty = true;
  33681. },
  33682. enumerable: true,
  33683. configurable: true
  33684. });
  33685. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  33686. /**
  33687. * Gets the global Saturation value.
  33688. * 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.
  33689. */
  33690. get: function () {
  33691. return this._globalSaturation;
  33692. },
  33693. /**
  33694. * Sets the global Saturation value.
  33695. * 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.
  33696. */
  33697. set: function (value) {
  33698. this._globalSaturation = value;
  33699. this._dirty = true;
  33700. },
  33701. enumerable: true,
  33702. configurable: true
  33703. });
  33704. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  33705. /**
  33706. * Gets the highlights Hue value.
  33707. * 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).
  33708. */
  33709. get: function () {
  33710. return this._highlightsHue;
  33711. },
  33712. /**
  33713. * Sets the highlights Hue value.
  33714. * 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).
  33715. */
  33716. set: function (value) {
  33717. this._highlightsHue = value;
  33718. this._dirty = true;
  33719. },
  33720. enumerable: true,
  33721. configurable: true
  33722. });
  33723. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  33724. /**
  33725. * Gets the highlights Density value.
  33726. * 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.
  33727. * Values less than zero provide a filter of opposite hue.
  33728. */
  33729. get: function () {
  33730. return this._highlightsDensity;
  33731. },
  33732. /**
  33733. * Sets the highlights Density value.
  33734. * 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.
  33735. * Values less than zero provide a filter of opposite hue.
  33736. */
  33737. set: function (value) {
  33738. this._highlightsDensity = value;
  33739. this._dirty = true;
  33740. },
  33741. enumerable: true,
  33742. configurable: true
  33743. });
  33744. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  33745. /**
  33746. * Gets the highlights Saturation value.
  33747. * 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.
  33748. */
  33749. get: function () {
  33750. return this._highlightsSaturation;
  33751. },
  33752. /**
  33753. * Sets the highlights Saturation value.
  33754. * 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.
  33755. */
  33756. set: function (value) {
  33757. this._highlightsSaturation = value;
  33758. this._dirty = true;
  33759. },
  33760. enumerable: true,
  33761. configurable: true
  33762. });
  33763. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  33764. /**
  33765. * Gets the highlights Exposure value.
  33766. * 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.
  33767. */
  33768. get: function () {
  33769. return this._highlightsExposure;
  33770. },
  33771. /**
  33772. * Sets the highlights Exposure value.
  33773. * 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.
  33774. */
  33775. set: function (value) {
  33776. this._highlightsExposure = value;
  33777. this._dirty = true;
  33778. },
  33779. enumerable: true,
  33780. configurable: true
  33781. });
  33782. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  33783. /**
  33784. * Gets the midtones Hue value.
  33785. * 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).
  33786. */
  33787. get: function () {
  33788. return this._midtonesHue;
  33789. },
  33790. /**
  33791. * Sets the midtones Hue value.
  33792. * 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).
  33793. */
  33794. set: function (value) {
  33795. this._midtonesHue = value;
  33796. this._dirty = true;
  33797. },
  33798. enumerable: true,
  33799. configurable: true
  33800. });
  33801. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  33802. /**
  33803. * Gets the midtones Density value.
  33804. * 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.
  33805. * Values less than zero provide a filter of opposite hue.
  33806. */
  33807. get: function () {
  33808. return this._midtonesDensity;
  33809. },
  33810. /**
  33811. * Sets the midtones Density value.
  33812. * 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.
  33813. * Values less than zero provide a filter of opposite hue.
  33814. */
  33815. set: function (value) {
  33816. this._midtonesDensity = value;
  33817. this._dirty = true;
  33818. },
  33819. enumerable: true,
  33820. configurable: true
  33821. });
  33822. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  33823. /**
  33824. * Gets the midtones Saturation value.
  33825. * 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.
  33826. */
  33827. get: function () {
  33828. return this._midtonesSaturation;
  33829. },
  33830. /**
  33831. * Sets the midtones Saturation value.
  33832. * 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.
  33833. */
  33834. set: function (value) {
  33835. this._midtonesSaturation = value;
  33836. this._dirty = true;
  33837. },
  33838. enumerable: true,
  33839. configurable: true
  33840. });
  33841. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  33842. /**
  33843. * Gets the midtones Exposure value.
  33844. * 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.
  33845. */
  33846. get: function () {
  33847. return this._midtonesExposure;
  33848. },
  33849. /**
  33850. * Sets the midtones Exposure value.
  33851. * 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.
  33852. */
  33853. set: function (value) {
  33854. this._midtonesExposure = value;
  33855. this._dirty = true;
  33856. },
  33857. enumerable: true,
  33858. configurable: true
  33859. });
  33860. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  33861. /**
  33862. * Gets the shadows Hue value.
  33863. * 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).
  33864. */
  33865. get: function () {
  33866. return this._shadowsHue;
  33867. },
  33868. /**
  33869. * Sets the shadows Hue value.
  33870. * 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).
  33871. */
  33872. set: function (value) {
  33873. this._shadowsHue = value;
  33874. this._dirty = true;
  33875. },
  33876. enumerable: true,
  33877. configurable: true
  33878. });
  33879. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  33880. /**
  33881. * Gets the shadows Density value.
  33882. * 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.
  33883. * Values less than zero provide a filter of opposite hue.
  33884. */
  33885. get: function () {
  33886. return this._shadowsDensity;
  33887. },
  33888. /**
  33889. * Sets the shadows Density value.
  33890. * 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.
  33891. * Values less than zero provide a filter of opposite hue.
  33892. */
  33893. set: function (value) {
  33894. this._shadowsDensity = value;
  33895. this._dirty = true;
  33896. },
  33897. enumerable: true,
  33898. configurable: true
  33899. });
  33900. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  33901. /**
  33902. * Gets the shadows Saturation value.
  33903. * 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.
  33904. */
  33905. get: function () {
  33906. return this._shadowsSaturation;
  33907. },
  33908. /**
  33909. * Sets the shadows Saturation value.
  33910. * 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.
  33911. */
  33912. set: function (value) {
  33913. this._shadowsSaturation = value;
  33914. this._dirty = true;
  33915. },
  33916. enumerable: true,
  33917. configurable: true
  33918. });
  33919. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  33920. /**
  33921. * Gets the shadows Exposure value.
  33922. * 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.
  33923. */
  33924. get: function () {
  33925. return this._shadowsExposure;
  33926. },
  33927. /**
  33928. * Sets the shadows Exposure value.
  33929. * 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.
  33930. */
  33931. set: function (value) {
  33932. this._shadowsExposure = value;
  33933. this._dirty = true;
  33934. },
  33935. enumerable: true,
  33936. configurable: true
  33937. });
  33938. ColorCurves.prototype.getClassName = function () {
  33939. return "ColorCurves";
  33940. };
  33941. /**
  33942. * Binds the color curves to the shader.
  33943. * @param colorCurves The color curve to bind
  33944. * @param effect The effect to bind to
  33945. */
  33946. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  33947. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  33948. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  33949. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  33950. if (colorCurves._dirty) {
  33951. colorCurves._dirty = false;
  33952. // Fill in global info.
  33953. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  33954. // Compute highlights info.
  33955. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  33956. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  33957. // Compute midtones info.
  33958. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  33959. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  33960. // Compute shadows info.
  33961. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  33962. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  33963. // Compute deltas (neutral is midtones).
  33964. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  33965. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  33966. }
  33967. if (effect) {
  33968. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  33969. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  33970. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  33971. }
  33972. };
  33973. /**
  33974. * Prepare the list of uniforms associated with the ColorCurves effects.
  33975. * @param uniformsList The list of uniforms used in the effect
  33976. */
  33977. ColorCurves.PrepareUniforms = function (uniformsList) {
  33978. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  33979. };
  33980. /**
  33981. * Returns color grading data based on a hue, density, saturation and exposure value.
  33982. * @param filterHue The hue of the color filter.
  33983. * @param filterDensity The density of the color filter.
  33984. * @param saturation The saturation.
  33985. * @param exposure The exposure.
  33986. * @param result The result data container.
  33987. */
  33988. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  33989. if (hue == null) {
  33990. return;
  33991. }
  33992. hue = ColorCurves.clamp(hue, 0, 360);
  33993. density = ColorCurves.clamp(density, -100, 100);
  33994. saturation = ColorCurves.clamp(saturation, -100, 100);
  33995. exposure = ColorCurves.clamp(exposure, -100, 100);
  33996. // Remap the slider/config filter density with non-linear mapping and also scale by half
  33997. // so that the maximum filter density is only 50% control. This provides fine control
  33998. // for small values and reasonable range.
  33999. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  34000. density *= 0.5;
  34001. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  34002. if (density < 0) {
  34003. density *= -1;
  34004. hue = (hue + 180) % 360;
  34005. }
  34006. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  34007. result.scaleToRef(2, result);
  34008. result.a = 1 + 0.01 * saturation;
  34009. };
  34010. /**
  34011. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  34012. * @param value The input slider value in range [-100,100].
  34013. * @returns Adjusted value.
  34014. */
  34015. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  34016. value /= 100;
  34017. var x = Math.abs(value);
  34018. x = Math.pow(x, 2);
  34019. if (value < 0) {
  34020. x *= -1;
  34021. }
  34022. x *= 100;
  34023. return x;
  34024. };
  34025. /**
  34026. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  34027. * @param hue The hue (H) input.
  34028. * @param saturation The saturation (S) input.
  34029. * @param brightness The brightness (B) input.
  34030. * @result An RGBA color represented as Vector4.
  34031. */
  34032. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  34033. var h = ColorCurves.clamp(hue, 0, 360);
  34034. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  34035. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  34036. if (s === 0) {
  34037. result.r = v;
  34038. result.g = v;
  34039. result.b = v;
  34040. }
  34041. else {
  34042. // sector 0 to 5
  34043. h /= 60;
  34044. var i = Math.floor(h);
  34045. // fractional part of h
  34046. var f = h - i;
  34047. var p = v * (1 - s);
  34048. var q = v * (1 - s * f);
  34049. var t = v * (1 - s * (1 - f));
  34050. switch (i) {
  34051. case 0:
  34052. result.r = v;
  34053. result.g = t;
  34054. result.b = p;
  34055. break;
  34056. case 1:
  34057. result.r = q;
  34058. result.g = v;
  34059. result.b = p;
  34060. break;
  34061. case 2:
  34062. result.r = p;
  34063. result.g = v;
  34064. result.b = t;
  34065. break;
  34066. case 3:
  34067. result.r = p;
  34068. result.g = q;
  34069. result.b = v;
  34070. break;
  34071. case 4:
  34072. result.r = t;
  34073. result.g = p;
  34074. result.b = v;
  34075. break;
  34076. default:// case 5:
  34077. result.r = v;
  34078. result.g = p;
  34079. result.b = q;
  34080. break;
  34081. }
  34082. }
  34083. result.a = 1;
  34084. };
  34085. /**
  34086. * Returns a value clamped between min and max
  34087. * @param value The value to clamp
  34088. * @param min The minimum of value
  34089. * @param max The maximum of value
  34090. * @returns The clamped value.
  34091. */
  34092. ColorCurves.clamp = function (value, min, max) {
  34093. return Math.min(Math.max(value, min), max);
  34094. };
  34095. /**
  34096. * Clones the current color curve instance.
  34097. * @return The cloned curves
  34098. */
  34099. ColorCurves.prototype.clone = function () {
  34100. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  34101. };
  34102. /**
  34103. * Serializes the current color curve instance to a json representation.
  34104. * @return a JSON representation
  34105. */
  34106. ColorCurves.prototype.serialize = function () {
  34107. return BABYLON.SerializationHelper.Serialize(this);
  34108. };
  34109. /**
  34110. * Parses the color curve from a json representation.
  34111. * @param source the JSON source to parse
  34112. * @return The parsed curves
  34113. */
  34114. ColorCurves.Parse = function (source) {
  34115. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  34116. };
  34117. __decorate([
  34118. BABYLON.serialize()
  34119. ], ColorCurves.prototype, "_globalHue", void 0);
  34120. __decorate([
  34121. BABYLON.serialize()
  34122. ], ColorCurves.prototype, "_globalDensity", void 0);
  34123. __decorate([
  34124. BABYLON.serialize()
  34125. ], ColorCurves.prototype, "_globalSaturation", void 0);
  34126. __decorate([
  34127. BABYLON.serialize()
  34128. ], ColorCurves.prototype, "_globalExposure", void 0);
  34129. __decorate([
  34130. BABYLON.serialize()
  34131. ], ColorCurves.prototype, "_highlightsHue", void 0);
  34132. __decorate([
  34133. BABYLON.serialize()
  34134. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  34135. __decorate([
  34136. BABYLON.serialize()
  34137. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  34138. __decorate([
  34139. BABYLON.serialize()
  34140. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  34141. __decorate([
  34142. BABYLON.serialize()
  34143. ], ColorCurves.prototype, "_midtonesHue", void 0);
  34144. __decorate([
  34145. BABYLON.serialize()
  34146. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  34147. __decorate([
  34148. BABYLON.serialize()
  34149. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  34150. __decorate([
  34151. BABYLON.serialize()
  34152. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  34153. return ColorCurves;
  34154. }());
  34155. BABYLON.ColorCurves = ColorCurves;
  34156. })(BABYLON || (BABYLON = {}));
  34157. //# sourceMappingURL=babylon.colorCurves.js.map
  34158. var BABYLON;
  34159. (function (BABYLON) {
  34160. var MaterialHelper = /** @class */ (function () {
  34161. function MaterialHelper() {
  34162. }
  34163. MaterialHelper.BindEyePosition = function (effect, scene) {
  34164. if (scene._forcedViewPosition) {
  34165. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  34166. return;
  34167. }
  34168. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  34169. };
  34170. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  34171. defines._needUVs = true;
  34172. defines[key] = true;
  34173. if (texture.getTextureMatrix().isIdentity(true)) {
  34174. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  34175. if (texture.coordinatesIndex === 0) {
  34176. defines["MAINUV1"] = true;
  34177. }
  34178. else {
  34179. defines["MAINUV2"] = true;
  34180. }
  34181. }
  34182. else {
  34183. defines[key + "DIRECTUV"] = 0;
  34184. }
  34185. };
  34186. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  34187. var matrix = texture.getTextureMatrix();
  34188. if (!matrix.isIdentity(true)) {
  34189. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  34190. }
  34191. };
  34192. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, defines) {
  34193. if (defines._areMiscDirty) {
  34194. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  34195. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  34196. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  34197. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  34198. }
  34199. };
  34200. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, forceAlphaTest) {
  34201. if (forceAlphaTest === void 0) { forceAlphaTest = false; }
  34202. var changed = false;
  34203. if (defines["CLIPPLANE"] !== (scene.clipPlane !== undefined && scene.clipPlane !== null)) {
  34204. defines["CLIPPLANE"] = !defines["CLIPPLANE"];
  34205. changed = true;
  34206. }
  34207. if (defines["ALPHATEST"] !== (engine.getAlphaTesting() || forceAlphaTest)) {
  34208. defines["ALPHATEST"] = !defines["ALPHATEST"];
  34209. changed = true;
  34210. }
  34211. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  34212. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  34213. changed = true;
  34214. }
  34215. if (defines["INSTANCES"] !== useInstances) {
  34216. defines["INSTANCES"] = useInstances;
  34217. changed = true;
  34218. }
  34219. if (changed) {
  34220. defines.markAsUnprocessed();
  34221. }
  34222. };
  34223. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  34224. if (useMorphTargets === void 0) { useMorphTargets = false; }
  34225. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  34226. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  34227. return false;
  34228. }
  34229. defines._normals = defines._needNormals;
  34230. defines._uvs = defines._needUVs;
  34231. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  34232. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  34233. defines["TANGENT"] = true;
  34234. }
  34235. if (defines._needUVs) {
  34236. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  34237. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  34238. }
  34239. else {
  34240. defines["UV1"] = false;
  34241. defines["UV2"] = false;
  34242. }
  34243. if (useVertexColor) {
  34244. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  34245. defines["VERTEXCOLOR"] = hasVertexColors;
  34246. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  34247. }
  34248. if (useBones) {
  34249. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  34250. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  34251. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  34252. }
  34253. else {
  34254. defines["NUM_BONE_INFLUENCERS"] = 0;
  34255. defines["BonesPerMesh"] = 0;
  34256. }
  34257. }
  34258. if (useMorphTargets) {
  34259. var manager = mesh.morphTargetManager;
  34260. if (manager) {
  34261. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  34262. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  34263. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  34264. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  34265. }
  34266. else {
  34267. defines["MORPHTARGETS_TANGENT"] = false;
  34268. defines["MORPHTARGETS_NORMAL"] = false;
  34269. defines["MORPHTARGETS"] = false;
  34270. defines["NUM_MORPH_INFLUENCERS"] = 0;
  34271. }
  34272. }
  34273. return true;
  34274. };
  34275. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  34276. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  34277. if (disableLighting === void 0) { disableLighting = false; }
  34278. if (!defines._areLightsDirty) {
  34279. return defines._needNormals;
  34280. }
  34281. var lightIndex = 0;
  34282. var needNormals = false;
  34283. var needRebuild = false;
  34284. var lightmapMode = false;
  34285. var shadowEnabled = false;
  34286. var specularEnabled = false;
  34287. if (scene.lightsEnabled && !disableLighting) {
  34288. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  34289. var light = _a[_i];
  34290. needNormals = true;
  34291. if (defines["LIGHT" + lightIndex] === undefined) {
  34292. needRebuild = true;
  34293. }
  34294. defines["LIGHT" + lightIndex] = true;
  34295. defines["SPOTLIGHT" + lightIndex] = false;
  34296. defines["HEMILIGHT" + lightIndex] = false;
  34297. defines["POINTLIGHT" + lightIndex] = false;
  34298. defines["DIRLIGHT" + lightIndex] = false;
  34299. var type;
  34300. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  34301. type = "SPOTLIGHT" + lightIndex;
  34302. }
  34303. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  34304. type = "HEMILIGHT" + lightIndex;
  34305. }
  34306. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  34307. type = "POINTLIGHT" + lightIndex;
  34308. }
  34309. else {
  34310. type = "DIRLIGHT" + lightIndex;
  34311. }
  34312. defines[type] = true;
  34313. // Specular
  34314. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  34315. specularEnabled = true;
  34316. }
  34317. // Shadows
  34318. defines["SHADOW" + lightIndex] = false;
  34319. defines["SHADOWPCF" + lightIndex] = false;
  34320. defines["SHADOWESM" + lightIndex] = false;
  34321. defines["SHADOWCUBE" + lightIndex] = false;
  34322. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  34323. var shadowGenerator = light.getShadowGenerator();
  34324. if (shadowGenerator) {
  34325. shadowEnabled = true;
  34326. shadowGenerator.prepareDefines(defines, lightIndex);
  34327. }
  34328. }
  34329. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  34330. lightmapMode = true;
  34331. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  34332. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  34333. }
  34334. else {
  34335. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  34336. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  34337. }
  34338. lightIndex++;
  34339. if (lightIndex === maxSimultaneousLights)
  34340. break;
  34341. }
  34342. }
  34343. defines["SPECULARTERM"] = specularEnabled;
  34344. defines["SHADOWS"] = shadowEnabled;
  34345. // Resetting all other lights if any
  34346. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  34347. if (defines["LIGHT" + index] !== undefined) {
  34348. defines["LIGHT" + index] = false;
  34349. defines["HEMILIGHT" + lightIndex] = false;
  34350. defines["POINTLIGHT" + lightIndex] = false;
  34351. defines["DIRLIGHT" + lightIndex] = false;
  34352. defines["SPOTLIGHT" + lightIndex] = false;
  34353. defines["SHADOW" + lightIndex] = false;
  34354. }
  34355. }
  34356. var caps = scene.getEngine().getCaps();
  34357. if (defines["SHADOWFLOAT"] === undefined) {
  34358. needRebuild = true;
  34359. }
  34360. defines["SHADOWFLOAT"] = shadowEnabled &&
  34361. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  34362. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  34363. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  34364. if (needRebuild) {
  34365. defines.rebuild();
  34366. }
  34367. return needNormals;
  34368. };
  34369. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  34370. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  34371. var uniformsList;
  34372. var uniformBuffersList = null;
  34373. if (uniformsListOrOptions.uniformsNames) {
  34374. var options = uniformsListOrOptions;
  34375. uniformsList = options.uniformsNames;
  34376. uniformBuffersList = options.uniformBuffersNames;
  34377. samplersList = options.samplers;
  34378. defines = options.defines;
  34379. maxSimultaneousLights = options.maxSimultaneousLights;
  34380. }
  34381. else {
  34382. uniformsList = uniformsListOrOptions;
  34383. if (!samplersList) {
  34384. samplersList = [];
  34385. }
  34386. }
  34387. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  34388. if (!defines["LIGHT" + lightIndex]) {
  34389. break;
  34390. }
  34391. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  34392. if (uniformBuffersList) {
  34393. uniformBuffersList.push("Light" + lightIndex);
  34394. }
  34395. samplersList.push("shadowSampler" + lightIndex);
  34396. }
  34397. if (defines["NUM_MORPH_INFLUENCERS"]) {
  34398. uniformsList.push("morphTargetInfluences");
  34399. }
  34400. };
  34401. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  34402. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  34403. if (rank === void 0) { rank = 0; }
  34404. var lightFallbackRank = 0;
  34405. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  34406. if (!defines["LIGHT" + lightIndex]) {
  34407. break;
  34408. }
  34409. if (lightIndex > 0) {
  34410. lightFallbackRank = rank + lightIndex;
  34411. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  34412. }
  34413. if (!defines["SHADOWS"]) {
  34414. if (defines["SHADOW" + lightIndex]) {
  34415. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  34416. }
  34417. if (defines["SHADOWPCF" + lightIndex]) {
  34418. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  34419. }
  34420. if (defines["SHADOWESM" + lightIndex]) {
  34421. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  34422. }
  34423. }
  34424. }
  34425. return lightFallbackRank++;
  34426. };
  34427. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  34428. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  34429. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  34430. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  34431. var manager = mesh.morphTargetManager;
  34432. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  34433. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  34434. for (var index = 0; index < influencers; index++) {
  34435. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  34436. if (normal) {
  34437. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  34438. }
  34439. if (tangent) {
  34440. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  34441. }
  34442. if (attribs.length > maxAttributesCount) {
  34443. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  34444. }
  34445. }
  34446. }
  34447. };
  34448. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  34449. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  34450. fallbacks.addCPUSkinningFallback(0, mesh);
  34451. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  34452. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  34453. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  34454. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  34455. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  34456. }
  34457. }
  34458. };
  34459. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  34460. if (defines["INSTANCES"]) {
  34461. attribs.push("world0");
  34462. attribs.push("world1");
  34463. attribs.push("world2");
  34464. attribs.push("world3");
  34465. }
  34466. };
  34467. // Bindings
  34468. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  34469. if (light.shadowEnabled && mesh.receiveShadows) {
  34470. var shadowGenerator = light.getShadowGenerator();
  34471. if (shadowGenerator) {
  34472. shadowGenerator.bindShadowLight(lightIndex, effect);
  34473. }
  34474. }
  34475. };
  34476. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  34477. light.transferToEffect(effect, lightIndex + "");
  34478. };
  34479. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  34480. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  34481. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  34482. for (var i = 0, len = mesh._lightSources.length, light, iAsString; i < len; i++) {
  34483. light = mesh._lightSources[i];
  34484. iAsString = i.toString();
  34485. var scaledIntensity = light.getScaledIntensity();
  34486. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  34487. MaterialHelper.BindLightProperties(light, effect, i);
  34488. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  34489. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  34490. if (defines["SPECULARTERM"]) {
  34491. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  34492. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  34493. }
  34494. // Shadows
  34495. if (scene.shadowsEnabled === true) {
  34496. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  34497. }
  34498. light._uniformBuffer.update();
  34499. if (i === maxSimultaneousLights)
  34500. break;
  34501. }
  34502. };
  34503. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  34504. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  34505. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  34506. effect.setColor3("vFogColor", scene.fogColor);
  34507. }
  34508. };
  34509. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  34510. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  34511. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  34512. if (matrices && effect) {
  34513. effect.setMatrices("mBones", matrices);
  34514. }
  34515. }
  34516. };
  34517. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  34518. var manager = abstractMesh.morphTargetManager;
  34519. if (!abstractMesh || !manager) {
  34520. return;
  34521. }
  34522. effect.setFloatArray("morphTargetInfluences", manager.influences);
  34523. };
  34524. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  34525. if (defines["LOGARITHMICDEPTH"]) {
  34526. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  34527. }
  34528. };
  34529. MaterialHelper.BindClipPlane = function (effect, scene) {
  34530. if (scene.clipPlane) {
  34531. var clipPlane = scene.clipPlane;
  34532. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  34533. }
  34534. };
  34535. return MaterialHelper;
  34536. }());
  34537. BABYLON.MaterialHelper = MaterialHelper;
  34538. })(BABYLON || (BABYLON = {}));
  34539. //# sourceMappingURL=babylon.materialHelper.js.map
  34540. var BABYLON;
  34541. (function (BABYLON) {
  34542. var PushMaterial = /** @class */ (function (_super) {
  34543. __extends(PushMaterial, _super);
  34544. function PushMaterial(name, scene) {
  34545. var _this = _super.call(this, name, scene) || this;
  34546. _this.storeEffectOnSubMeshes = true;
  34547. return _this;
  34548. }
  34549. PushMaterial.prototype.getEffect = function () {
  34550. return this._activeEffect;
  34551. };
  34552. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  34553. if (!mesh) {
  34554. return false;
  34555. }
  34556. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  34557. return true;
  34558. }
  34559. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  34560. };
  34561. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  34562. this._activeEffect.setMatrix("world", world);
  34563. };
  34564. PushMaterial.prototype.bind = function (world, mesh) {
  34565. if (!mesh) {
  34566. return;
  34567. }
  34568. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  34569. };
  34570. PushMaterial.prototype._afterBind = function (mesh, effect) {
  34571. if (effect === void 0) { effect = null; }
  34572. _super.prototype._afterBind.call(this, mesh);
  34573. this.getScene()._cachedEffect = effect;
  34574. };
  34575. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  34576. if (visibility === void 0) { visibility = 1; }
  34577. return scene.isCachedMaterialInvalid(this, effect, visibility);
  34578. };
  34579. return PushMaterial;
  34580. }(BABYLON.Material));
  34581. BABYLON.PushMaterial = PushMaterial;
  34582. })(BABYLON || (BABYLON = {}));
  34583. //# sourceMappingURL=babylon.pushMaterial.js.map
  34584. var BABYLON;
  34585. (function (BABYLON) {
  34586. var StandardMaterialDefines = /** @class */ (function (_super) {
  34587. __extends(StandardMaterialDefines, _super);
  34588. function StandardMaterialDefines() {
  34589. var _this = _super.call(this) || this;
  34590. _this.MAINUV1 = false;
  34591. _this.MAINUV2 = false;
  34592. _this.DIFFUSE = false;
  34593. _this.DIFFUSEDIRECTUV = 0;
  34594. _this.AMBIENT = false;
  34595. _this.AMBIENTDIRECTUV = 0;
  34596. _this.OPACITY = false;
  34597. _this.OPACITYDIRECTUV = 0;
  34598. _this.OPACITYRGB = false;
  34599. _this.REFLECTION = false;
  34600. _this.EMISSIVE = false;
  34601. _this.EMISSIVEDIRECTUV = 0;
  34602. _this.SPECULAR = false;
  34603. _this.SPECULARDIRECTUV = 0;
  34604. _this.BUMP = false;
  34605. _this.BUMPDIRECTUV = 0;
  34606. _this.PARALLAX = false;
  34607. _this.PARALLAXOCCLUSION = false;
  34608. _this.SPECULAROVERALPHA = false;
  34609. _this.CLIPPLANE = false;
  34610. _this.ALPHATEST = false;
  34611. _this.DEPTHPREPASS = false;
  34612. _this.ALPHAFROMDIFFUSE = false;
  34613. _this.POINTSIZE = false;
  34614. _this.FOG = false;
  34615. _this.SPECULARTERM = false;
  34616. _this.DIFFUSEFRESNEL = false;
  34617. _this.OPACITYFRESNEL = false;
  34618. _this.REFLECTIONFRESNEL = false;
  34619. _this.REFRACTIONFRESNEL = false;
  34620. _this.EMISSIVEFRESNEL = false;
  34621. _this.FRESNEL = false;
  34622. _this.NORMAL = false;
  34623. _this.UV1 = false;
  34624. _this.UV2 = false;
  34625. _this.VERTEXCOLOR = false;
  34626. _this.VERTEXALPHA = false;
  34627. _this.NUM_BONE_INFLUENCERS = 0;
  34628. _this.BonesPerMesh = 0;
  34629. _this.INSTANCES = false;
  34630. _this.GLOSSINESS = false;
  34631. _this.ROUGHNESS = false;
  34632. _this.EMISSIVEASILLUMINATION = false;
  34633. _this.LINKEMISSIVEWITHDIFFUSE = false;
  34634. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  34635. _this.LIGHTMAP = false;
  34636. _this.LIGHTMAPDIRECTUV = 0;
  34637. _this.USELIGHTMAPASSHADOWMAP = false;
  34638. _this.REFLECTIONMAP_3D = false;
  34639. _this.REFLECTIONMAP_SPHERICAL = false;
  34640. _this.REFLECTIONMAP_PLANAR = false;
  34641. _this.REFLECTIONMAP_CUBIC = false;
  34642. _this.REFLECTIONMAP_PROJECTION = false;
  34643. _this.REFLECTIONMAP_SKYBOX = false;
  34644. _this.REFLECTIONMAP_EXPLICIT = false;
  34645. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  34646. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  34647. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  34648. _this.INVERTCUBICMAP = false;
  34649. _this.LOGARITHMICDEPTH = false;
  34650. _this.REFRACTION = false;
  34651. _this.REFRACTIONMAP_3D = false;
  34652. _this.REFLECTIONOVERALPHA = false;
  34653. _this.TWOSIDEDLIGHTING = false;
  34654. _this.SHADOWFLOAT = false;
  34655. _this.MORPHTARGETS = false;
  34656. _this.MORPHTARGETS_NORMAL = false;
  34657. _this.MORPHTARGETS_TANGENT = false;
  34658. _this.NUM_MORPH_INFLUENCERS = 0;
  34659. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  34660. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  34661. _this.IMAGEPROCESSING = false;
  34662. _this.VIGNETTE = false;
  34663. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  34664. _this.VIGNETTEBLENDMODEOPAQUE = false;
  34665. _this.TONEMAPPING = false;
  34666. _this.CONTRAST = false;
  34667. _this.COLORCURVES = false;
  34668. _this.COLORGRADING = false;
  34669. _this.COLORGRADING3D = false;
  34670. _this.SAMPLER3DGREENDEPTH = false;
  34671. _this.SAMPLER3DBGRMAP = false;
  34672. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  34673. _this.EXPOSURE = false;
  34674. _this.rebuild();
  34675. return _this;
  34676. }
  34677. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  34678. var modes = [
  34679. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  34680. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  34681. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  34682. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  34683. ];
  34684. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  34685. var mode = modes_1[_i];
  34686. this[mode] = (mode === modeToEnable);
  34687. }
  34688. };
  34689. return StandardMaterialDefines;
  34690. }(BABYLON.MaterialDefines));
  34691. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  34692. var StandardMaterial = /** @class */ (function (_super) {
  34693. __extends(StandardMaterial, _super);
  34694. function StandardMaterial(name, scene) {
  34695. var _this = _super.call(this, name, scene) || this;
  34696. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  34697. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  34698. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  34699. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  34700. _this.specularPower = 64;
  34701. _this._useAlphaFromDiffuseTexture = false;
  34702. _this._useEmissiveAsIllumination = false;
  34703. _this._linkEmissiveWithDiffuse = false;
  34704. _this._useSpecularOverAlpha = false;
  34705. _this._useReflectionOverAlpha = false;
  34706. _this._disableLighting = false;
  34707. _this._useParallax = false;
  34708. _this._useParallaxOcclusion = false;
  34709. _this.parallaxScaleBias = 0.05;
  34710. _this._roughness = 0;
  34711. _this.indexOfRefraction = 0.98;
  34712. _this.invertRefractionY = true;
  34713. _this._useLightmapAsShadowmap = false;
  34714. _this._useReflectionFresnelFromSpecular = false;
  34715. _this._useGlossinessFromSpecularMapAlpha = false;
  34716. _this._maxSimultaneousLights = 4;
  34717. /**
  34718. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  34719. */
  34720. _this._invertNormalMapX = false;
  34721. /**
  34722. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  34723. */
  34724. _this._invertNormalMapY = false;
  34725. /**
  34726. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  34727. */
  34728. _this._twoSidedLighting = false;
  34729. _this._renderTargets = new BABYLON.SmartArray(16);
  34730. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  34731. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  34732. // Setup the default processing configuration to the scene.
  34733. _this._attachImageProcessingConfiguration(null);
  34734. _this.getRenderTargetTextures = function () {
  34735. _this._renderTargets.reset();
  34736. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  34737. _this._renderTargets.push(_this._reflectionTexture);
  34738. }
  34739. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  34740. _this._renderTargets.push(_this._refractionTexture);
  34741. }
  34742. return _this._renderTargets;
  34743. };
  34744. return _this;
  34745. }
  34746. ;
  34747. ;
  34748. ;
  34749. ;
  34750. ;
  34751. ;
  34752. ;
  34753. ;
  34754. ;
  34755. ;
  34756. ;
  34757. ;
  34758. ;
  34759. ;
  34760. ;
  34761. ;
  34762. ;
  34763. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  34764. /**
  34765. * Gets the image processing configuration used either in this material.
  34766. */
  34767. get: function () {
  34768. return this._imageProcessingConfiguration;
  34769. },
  34770. /**
  34771. * Sets the Default image processing configuration used either in the this material.
  34772. *
  34773. * If sets to null, the scene one is in use.
  34774. */
  34775. set: function (value) {
  34776. this._attachImageProcessingConfiguration(value);
  34777. // Ensure the effect will be rebuilt.
  34778. this._markAllSubMeshesAsTexturesDirty();
  34779. },
  34780. enumerable: true,
  34781. configurable: true
  34782. });
  34783. /**
  34784. * Attaches a new image processing configuration to the Standard Material.
  34785. * @param configuration
  34786. */
  34787. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  34788. var _this = this;
  34789. if (configuration === this._imageProcessingConfiguration) {
  34790. return;
  34791. }
  34792. // Detaches observer.
  34793. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  34794. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  34795. }
  34796. // Pick the scene configuration if needed.
  34797. if (!configuration) {
  34798. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  34799. }
  34800. else {
  34801. this._imageProcessingConfiguration = configuration;
  34802. }
  34803. // Attaches observer.
  34804. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  34805. _this._markAllSubMeshesAsImageProcessingDirty();
  34806. });
  34807. };
  34808. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  34809. /**
  34810. * Gets wether the color curves effect is enabled.
  34811. */
  34812. get: function () {
  34813. return this.imageProcessingConfiguration.colorCurvesEnabled;
  34814. },
  34815. /**
  34816. * Sets wether the color curves effect is enabled.
  34817. */
  34818. set: function (value) {
  34819. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  34820. },
  34821. enumerable: true,
  34822. configurable: true
  34823. });
  34824. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  34825. /**
  34826. * Gets wether the color grading effect is enabled.
  34827. */
  34828. get: function () {
  34829. return this.imageProcessingConfiguration.colorGradingEnabled;
  34830. },
  34831. /**
  34832. * Gets wether the color grading effect is enabled.
  34833. */
  34834. set: function (value) {
  34835. this.imageProcessingConfiguration.colorGradingEnabled = value;
  34836. },
  34837. enumerable: true,
  34838. configurable: true
  34839. });
  34840. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  34841. /**
  34842. * Gets wether tonemapping is enabled or not.
  34843. */
  34844. get: function () {
  34845. return this._imageProcessingConfiguration.toneMappingEnabled;
  34846. },
  34847. /**
  34848. * Sets wether tonemapping is enabled or not
  34849. */
  34850. set: function (value) {
  34851. this._imageProcessingConfiguration.toneMappingEnabled = value;
  34852. },
  34853. enumerable: true,
  34854. configurable: true
  34855. });
  34856. ;
  34857. ;
  34858. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  34859. /**
  34860. * The camera exposure used on this material.
  34861. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  34862. * This corresponds to a photographic exposure.
  34863. */
  34864. get: function () {
  34865. return this._imageProcessingConfiguration.exposure;
  34866. },
  34867. /**
  34868. * The camera exposure used on this material.
  34869. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  34870. * This corresponds to a photographic exposure.
  34871. */
  34872. set: function (value) {
  34873. this._imageProcessingConfiguration.exposure = value;
  34874. },
  34875. enumerable: true,
  34876. configurable: true
  34877. });
  34878. ;
  34879. ;
  34880. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  34881. /**
  34882. * Gets The camera contrast used on this material.
  34883. */
  34884. get: function () {
  34885. return this._imageProcessingConfiguration.contrast;
  34886. },
  34887. /**
  34888. * Sets The camera contrast used on this material.
  34889. */
  34890. set: function (value) {
  34891. this._imageProcessingConfiguration.contrast = value;
  34892. },
  34893. enumerable: true,
  34894. configurable: true
  34895. });
  34896. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  34897. /**
  34898. * Gets the Color Grading 2D Lookup Texture.
  34899. */
  34900. get: function () {
  34901. return this._imageProcessingConfiguration.colorGradingTexture;
  34902. },
  34903. /**
  34904. * Sets the Color Grading 2D Lookup Texture.
  34905. */
  34906. set: function (value) {
  34907. this._imageProcessingConfiguration.colorGradingTexture = value;
  34908. },
  34909. enumerable: true,
  34910. configurable: true
  34911. });
  34912. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  34913. /**
  34914. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  34915. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  34916. * 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;
  34917. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  34918. */
  34919. get: function () {
  34920. return this._imageProcessingConfiguration.colorCurves;
  34921. },
  34922. /**
  34923. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  34924. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  34925. * 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;
  34926. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  34927. */
  34928. set: function (value) {
  34929. this._imageProcessingConfiguration.colorCurves = value;
  34930. },
  34931. enumerable: true,
  34932. configurable: true
  34933. });
  34934. StandardMaterial.prototype.getClassName = function () {
  34935. return "StandardMaterial";
  34936. };
  34937. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  34938. get: function () {
  34939. return this._useLogarithmicDepth;
  34940. },
  34941. set: function (value) {
  34942. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  34943. this._markAllSubMeshesAsMiscDirty();
  34944. },
  34945. enumerable: true,
  34946. configurable: true
  34947. });
  34948. StandardMaterial.prototype.needAlphaBlending = function () {
  34949. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  34950. };
  34951. StandardMaterial.prototype.needAlphaTesting = function () {
  34952. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  34953. };
  34954. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  34955. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  34956. };
  34957. StandardMaterial.prototype.getAlphaTestTexture = function () {
  34958. return this._diffuseTexture;
  34959. };
  34960. /**
  34961. * Child classes can use it to update shaders
  34962. */
  34963. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  34964. if (useInstances === void 0) { useInstances = false; }
  34965. if (subMesh.effect && this.isFrozen) {
  34966. if (this._wasPreviouslyReady && subMesh.effect) {
  34967. return true;
  34968. }
  34969. }
  34970. if (!subMesh._materialDefines) {
  34971. subMesh._materialDefines = new StandardMaterialDefines();
  34972. }
  34973. var scene = this.getScene();
  34974. var defines = subMesh._materialDefines;
  34975. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  34976. if (defines._renderId === scene.getRenderId()) {
  34977. return true;
  34978. }
  34979. }
  34980. var engine = scene.getEngine();
  34981. // Lights
  34982. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  34983. // Textures
  34984. if (defines._areTexturesDirty) {
  34985. defines._needUVs = false;
  34986. defines.MAINUV1 = false;
  34987. defines.MAINUV2 = false;
  34988. if (scene.texturesEnabled) {
  34989. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  34990. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  34991. return false;
  34992. }
  34993. else {
  34994. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  34995. }
  34996. }
  34997. else {
  34998. defines.DIFFUSE = false;
  34999. }
  35000. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  35001. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  35002. return false;
  35003. }
  35004. else {
  35005. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  35006. }
  35007. }
  35008. else {
  35009. defines.AMBIENT = false;
  35010. }
  35011. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  35012. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  35013. return false;
  35014. }
  35015. else {
  35016. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  35017. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  35018. }
  35019. }
  35020. else {
  35021. defines.OPACITY = false;
  35022. }
  35023. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  35024. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  35025. return false;
  35026. }
  35027. else {
  35028. defines._needNormals = true;
  35029. defines.REFLECTION = true;
  35030. defines.ROUGHNESS = (this._roughness > 0);
  35031. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  35032. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  35033. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  35034. switch (this._reflectionTexture.coordinatesMode) {
  35035. case BABYLON.Texture.CUBIC_MODE:
  35036. case BABYLON.Texture.INVCUBIC_MODE:
  35037. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  35038. break;
  35039. case BABYLON.Texture.EXPLICIT_MODE:
  35040. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  35041. break;
  35042. case BABYLON.Texture.PLANAR_MODE:
  35043. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  35044. break;
  35045. case BABYLON.Texture.PROJECTION_MODE:
  35046. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  35047. break;
  35048. case BABYLON.Texture.SKYBOX_MODE:
  35049. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  35050. break;
  35051. case BABYLON.Texture.SPHERICAL_MODE:
  35052. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  35053. break;
  35054. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  35055. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  35056. break;
  35057. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  35058. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  35059. break;
  35060. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  35061. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  35062. break;
  35063. }
  35064. }
  35065. }
  35066. else {
  35067. defines.REFLECTION = false;
  35068. }
  35069. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  35070. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  35071. return false;
  35072. }
  35073. else {
  35074. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  35075. }
  35076. }
  35077. else {
  35078. defines.EMISSIVE = false;
  35079. }
  35080. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  35081. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  35082. return false;
  35083. }
  35084. else {
  35085. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  35086. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  35087. }
  35088. }
  35089. else {
  35090. defines.LIGHTMAP = false;
  35091. }
  35092. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  35093. if (!this._specularTexture.isReadyOrNotBlocking()) {
  35094. return false;
  35095. }
  35096. else {
  35097. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  35098. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  35099. }
  35100. }
  35101. else {
  35102. defines.SPECULAR = false;
  35103. }
  35104. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  35105. // Bump texure can not be not blocking.
  35106. if (!this._bumpTexture.isReady()) {
  35107. return false;
  35108. }
  35109. else {
  35110. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  35111. defines.PARALLAX = this._useParallax;
  35112. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  35113. }
  35114. }
  35115. else {
  35116. defines.BUMP = false;
  35117. }
  35118. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  35119. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  35120. return false;
  35121. }
  35122. else {
  35123. defines._needUVs = true;
  35124. defines.REFRACTION = true;
  35125. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  35126. }
  35127. }
  35128. else {
  35129. defines.REFRACTION = false;
  35130. }
  35131. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  35132. }
  35133. else {
  35134. defines.DIFFUSE = false;
  35135. defines.AMBIENT = false;
  35136. defines.OPACITY = false;
  35137. defines.REFLECTION = false;
  35138. defines.EMISSIVE = false;
  35139. defines.LIGHTMAP = false;
  35140. defines.BUMP = false;
  35141. defines.REFRACTION = false;
  35142. }
  35143. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  35144. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  35145. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  35146. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  35147. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  35148. }
  35149. if (defines._areImageProcessingDirty) {
  35150. if (!this._imageProcessingConfiguration.isReady()) {
  35151. return false;
  35152. }
  35153. this._imageProcessingConfiguration.prepareDefines(defines);
  35154. }
  35155. if (defines._areFresnelDirty) {
  35156. if (StandardMaterial.FresnelEnabled) {
  35157. // Fresnel
  35158. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  35159. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  35160. this._reflectionFresnelParameters) {
  35161. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  35162. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  35163. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  35164. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  35165. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  35166. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  35167. defines._needNormals = true;
  35168. defines.FRESNEL = true;
  35169. }
  35170. }
  35171. else {
  35172. defines.FRESNEL = false;
  35173. }
  35174. }
  35175. // Misc.
  35176. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  35177. // Attribs
  35178. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  35179. // Values that need to be evaluated on every frame
  35180. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  35181. // Get correct effect
  35182. if (defines.isDirty) {
  35183. defines.markAsProcessed();
  35184. scene.resetCachedMaterial();
  35185. // Fallbacks
  35186. var fallbacks = new BABYLON.EffectFallbacks();
  35187. if (defines.REFLECTION) {
  35188. fallbacks.addFallback(0, "REFLECTION");
  35189. }
  35190. if (defines.SPECULAR) {
  35191. fallbacks.addFallback(0, "SPECULAR");
  35192. }
  35193. if (defines.BUMP) {
  35194. fallbacks.addFallback(0, "BUMP");
  35195. }
  35196. if (defines.PARALLAX) {
  35197. fallbacks.addFallback(1, "PARALLAX");
  35198. }
  35199. if (defines.PARALLAXOCCLUSION) {
  35200. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  35201. }
  35202. if (defines.SPECULAROVERALPHA) {
  35203. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  35204. }
  35205. if (defines.FOG) {
  35206. fallbacks.addFallback(1, "FOG");
  35207. }
  35208. if (defines.POINTSIZE) {
  35209. fallbacks.addFallback(0, "POINTSIZE");
  35210. }
  35211. if (defines.LOGARITHMICDEPTH) {
  35212. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  35213. }
  35214. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  35215. if (defines.SPECULARTERM) {
  35216. fallbacks.addFallback(0, "SPECULARTERM");
  35217. }
  35218. if (defines.DIFFUSEFRESNEL) {
  35219. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  35220. }
  35221. if (defines.OPACITYFRESNEL) {
  35222. fallbacks.addFallback(2, "OPACITYFRESNEL");
  35223. }
  35224. if (defines.REFLECTIONFRESNEL) {
  35225. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  35226. }
  35227. if (defines.EMISSIVEFRESNEL) {
  35228. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  35229. }
  35230. if (defines.FRESNEL) {
  35231. fallbacks.addFallback(4, "FRESNEL");
  35232. }
  35233. //Attributes
  35234. var attribs = [BABYLON.VertexBuffer.PositionKind];
  35235. if (defines.NORMAL) {
  35236. attribs.push(BABYLON.VertexBuffer.NormalKind);
  35237. }
  35238. if (defines.UV1) {
  35239. attribs.push(BABYLON.VertexBuffer.UVKind);
  35240. }
  35241. if (defines.UV2) {
  35242. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  35243. }
  35244. if (defines.VERTEXCOLOR) {
  35245. attribs.push(BABYLON.VertexBuffer.ColorKind);
  35246. }
  35247. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  35248. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  35249. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  35250. var shaderName = "default";
  35251. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  35252. "vFogInfos", "vFogColor", "pointSize",
  35253. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  35254. "mBones",
  35255. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  35256. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  35257. "logarithmicDepthConstant", "vTangentSpaceParams"
  35258. ];
  35259. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  35260. var uniformBuffers = ["Material", "Scene"];
  35261. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  35262. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  35263. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  35264. uniformsNames: uniforms,
  35265. uniformBuffersNames: uniformBuffers,
  35266. samplers: samplers,
  35267. defines: defines,
  35268. maxSimultaneousLights: this._maxSimultaneousLights
  35269. });
  35270. if (this.customShaderNameResolve) {
  35271. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  35272. }
  35273. var join = defines.toString();
  35274. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  35275. attributes: attribs,
  35276. uniformsNames: uniforms,
  35277. uniformBuffersNames: uniformBuffers,
  35278. samplers: samplers,
  35279. defines: join,
  35280. fallbacks: fallbacks,
  35281. onCompiled: this.onCompiled,
  35282. onError: this.onError,
  35283. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  35284. }, engine), defines);
  35285. this.buildUniformLayout();
  35286. }
  35287. if (!subMesh.effect || !subMesh.effect.isReady()) {
  35288. return false;
  35289. }
  35290. defines._renderId = scene.getRenderId();
  35291. this._wasPreviouslyReady = true;
  35292. return true;
  35293. };
  35294. StandardMaterial.prototype.buildUniformLayout = function () {
  35295. // Order is important !
  35296. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  35297. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  35298. this._uniformBuffer.addUniform("opacityParts", 4);
  35299. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  35300. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  35301. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  35302. this._uniformBuffer.addUniform("refractionRightColor", 4);
  35303. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  35304. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  35305. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  35306. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  35307. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  35308. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  35309. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  35310. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  35311. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  35312. this._uniformBuffer.addUniform("vBumpInfos", 3);
  35313. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  35314. this._uniformBuffer.addUniform("ambientMatrix", 16);
  35315. this._uniformBuffer.addUniform("opacityMatrix", 16);
  35316. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  35317. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  35318. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  35319. this._uniformBuffer.addUniform("specularMatrix", 16);
  35320. this._uniformBuffer.addUniform("bumpMatrix", 16);
  35321. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  35322. this._uniformBuffer.addUniform("refractionMatrix", 16);
  35323. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  35324. this._uniformBuffer.addUniform("vSpecularColor", 4);
  35325. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  35326. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  35327. this._uniformBuffer.addUniform("pointSize", 1);
  35328. this._uniformBuffer.create();
  35329. };
  35330. StandardMaterial.prototype.unbind = function () {
  35331. if (this._activeEffect) {
  35332. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  35333. this._activeEffect.setTexture("reflection2DSampler", null);
  35334. }
  35335. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  35336. this._activeEffect.setTexture("refraction2DSampler", null);
  35337. }
  35338. }
  35339. _super.prototype.unbind.call(this);
  35340. };
  35341. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  35342. var scene = this.getScene();
  35343. var defines = subMesh._materialDefines;
  35344. if (!defines) {
  35345. return;
  35346. }
  35347. var effect = subMesh.effect;
  35348. if (!effect) {
  35349. return;
  35350. }
  35351. this._activeEffect = effect;
  35352. // Matrices
  35353. this.bindOnlyWorldMatrix(world);
  35354. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  35355. // Bones
  35356. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  35357. if (mustRebind) {
  35358. this._uniformBuffer.bindToEffect(effect, "Material");
  35359. this.bindViewProjection(effect);
  35360. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  35361. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  35362. // Fresnel
  35363. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  35364. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  35365. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  35366. }
  35367. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  35368. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  35369. }
  35370. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  35371. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  35372. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  35373. }
  35374. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  35375. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  35376. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  35377. }
  35378. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  35379. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  35380. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  35381. }
  35382. }
  35383. // Textures
  35384. if (scene.texturesEnabled) {
  35385. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  35386. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  35387. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  35388. }
  35389. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  35390. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  35391. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  35392. }
  35393. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  35394. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  35395. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  35396. }
  35397. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  35398. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  35399. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  35400. }
  35401. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  35402. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  35403. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  35404. }
  35405. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  35406. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  35407. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  35408. }
  35409. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  35410. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  35411. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  35412. }
  35413. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  35414. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  35415. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  35416. if (scene._mirroredCameraPosition) {
  35417. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  35418. }
  35419. else {
  35420. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  35421. }
  35422. }
  35423. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  35424. var depth = 1.0;
  35425. if (!this._refractionTexture.isCube) {
  35426. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  35427. if (this._refractionTexture.depth) {
  35428. depth = this._refractionTexture.depth;
  35429. }
  35430. }
  35431. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  35432. }
  35433. }
  35434. // Point size
  35435. if (this.pointsCloud) {
  35436. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  35437. }
  35438. if (defines.SPECULARTERM) {
  35439. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  35440. }
  35441. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  35442. // Diffuse
  35443. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  35444. }
  35445. // Textures
  35446. if (scene.texturesEnabled) {
  35447. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  35448. effect.setTexture("diffuseSampler", this._diffuseTexture);
  35449. }
  35450. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  35451. effect.setTexture("ambientSampler", this._ambientTexture);
  35452. }
  35453. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  35454. effect.setTexture("opacitySampler", this._opacityTexture);
  35455. }
  35456. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  35457. if (this._reflectionTexture.isCube) {
  35458. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  35459. }
  35460. else {
  35461. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  35462. }
  35463. }
  35464. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  35465. effect.setTexture("emissiveSampler", this._emissiveTexture);
  35466. }
  35467. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  35468. effect.setTexture("lightmapSampler", this._lightmapTexture);
  35469. }
  35470. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  35471. effect.setTexture("specularSampler", this._specularTexture);
  35472. }
  35473. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  35474. effect.setTexture("bumpSampler", this._bumpTexture);
  35475. }
  35476. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  35477. var depth = 1.0;
  35478. if (this._refractionTexture.isCube) {
  35479. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  35480. }
  35481. else {
  35482. effect.setTexture("refraction2DSampler", this._refractionTexture);
  35483. }
  35484. }
  35485. }
  35486. // Clip plane
  35487. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  35488. // Colors
  35489. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  35490. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  35491. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  35492. }
  35493. if (mustRebind || !this.isFrozen) {
  35494. // Lights
  35495. if (scene.lightsEnabled && !this._disableLighting) {
  35496. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  35497. }
  35498. // View
  35499. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  35500. this.bindView(effect);
  35501. }
  35502. // Fog
  35503. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  35504. // Morph targets
  35505. if (defines.NUM_MORPH_INFLUENCERS) {
  35506. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  35507. }
  35508. // Log. depth
  35509. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  35510. // image processing
  35511. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  35512. this._imageProcessingConfiguration.bind(this._activeEffect);
  35513. }
  35514. }
  35515. this._uniformBuffer.update();
  35516. this._afterBind(mesh, this._activeEffect);
  35517. };
  35518. StandardMaterial.prototype.getAnimatables = function () {
  35519. var results = [];
  35520. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  35521. results.push(this._diffuseTexture);
  35522. }
  35523. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  35524. results.push(this._ambientTexture);
  35525. }
  35526. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  35527. results.push(this._opacityTexture);
  35528. }
  35529. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  35530. results.push(this._reflectionTexture);
  35531. }
  35532. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  35533. results.push(this._emissiveTexture);
  35534. }
  35535. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  35536. results.push(this._specularTexture);
  35537. }
  35538. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  35539. results.push(this._bumpTexture);
  35540. }
  35541. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  35542. results.push(this._lightmapTexture);
  35543. }
  35544. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  35545. results.push(this._refractionTexture);
  35546. }
  35547. return results;
  35548. };
  35549. StandardMaterial.prototype.getActiveTextures = function () {
  35550. var activeTextures = _super.prototype.getActiveTextures.call(this);
  35551. if (this._diffuseTexture) {
  35552. activeTextures.push(this._diffuseTexture);
  35553. }
  35554. if (this._ambientTexture) {
  35555. activeTextures.push(this._ambientTexture);
  35556. }
  35557. if (this._opacityTexture) {
  35558. activeTextures.push(this._opacityTexture);
  35559. }
  35560. if (this._reflectionTexture) {
  35561. activeTextures.push(this._reflectionTexture);
  35562. }
  35563. if (this._emissiveTexture) {
  35564. activeTextures.push(this._emissiveTexture);
  35565. }
  35566. if (this._specularTexture) {
  35567. activeTextures.push(this._specularTexture);
  35568. }
  35569. if (this._bumpTexture) {
  35570. activeTextures.push(this._bumpTexture);
  35571. }
  35572. if (this._lightmapTexture) {
  35573. activeTextures.push(this._lightmapTexture);
  35574. }
  35575. if (this._refractionTexture) {
  35576. activeTextures.push(this._refractionTexture);
  35577. }
  35578. return activeTextures;
  35579. };
  35580. StandardMaterial.prototype.hasTexture = function (texture) {
  35581. if (_super.prototype.hasTexture.call(this, texture)) {
  35582. return true;
  35583. }
  35584. if (this._diffuseTexture === texture) {
  35585. return true;
  35586. }
  35587. if (this._ambientTexture === texture) {
  35588. return true;
  35589. }
  35590. if (this._opacityTexture === texture) {
  35591. return true;
  35592. }
  35593. if (this._reflectionTexture === texture) {
  35594. return true;
  35595. }
  35596. if (this._emissiveTexture === texture) {
  35597. return true;
  35598. }
  35599. if (this._specularTexture === texture) {
  35600. return true;
  35601. }
  35602. if (this._bumpTexture === texture) {
  35603. return true;
  35604. }
  35605. if (this._lightmapTexture === texture) {
  35606. return true;
  35607. }
  35608. if (this._refractionTexture === texture) {
  35609. return true;
  35610. }
  35611. return false;
  35612. };
  35613. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  35614. if (forceDisposeTextures) {
  35615. if (this._diffuseTexture) {
  35616. this._diffuseTexture.dispose();
  35617. }
  35618. if (this._ambientTexture) {
  35619. this._ambientTexture.dispose();
  35620. }
  35621. if (this._opacityTexture) {
  35622. this._opacityTexture.dispose();
  35623. }
  35624. if (this._reflectionTexture) {
  35625. this._reflectionTexture.dispose();
  35626. }
  35627. if (this._emissiveTexture) {
  35628. this._emissiveTexture.dispose();
  35629. }
  35630. if (this._specularTexture) {
  35631. this._specularTexture.dispose();
  35632. }
  35633. if (this._bumpTexture) {
  35634. this._bumpTexture.dispose();
  35635. }
  35636. if (this._lightmapTexture) {
  35637. this._lightmapTexture.dispose();
  35638. }
  35639. if (this._refractionTexture) {
  35640. this._refractionTexture.dispose();
  35641. }
  35642. }
  35643. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  35644. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  35645. }
  35646. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  35647. };
  35648. StandardMaterial.prototype.clone = function (name) {
  35649. var _this = this;
  35650. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  35651. result.name = name;
  35652. result.id = name;
  35653. return result;
  35654. };
  35655. StandardMaterial.prototype.serialize = function () {
  35656. return BABYLON.SerializationHelper.Serialize(this);
  35657. };
  35658. // Statics
  35659. StandardMaterial.Parse = function (source, scene, rootUrl) {
  35660. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  35661. };
  35662. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  35663. get: function () {
  35664. return StandardMaterial._DiffuseTextureEnabled;
  35665. },
  35666. set: function (value) {
  35667. if (StandardMaterial._DiffuseTextureEnabled === value) {
  35668. return;
  35669. }
  35670. StandardMaterial._DiffuseTextureEnabled = value;
  35671. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35672. },
  35673. enumerable: true,
  35674. configurable: true
  35675. });
  35676. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  35677. get: function () {
  35678. return StandardMaterial._AmbientTextureEnabled;
  35679. },
  35680. set: function (value) {
  35681. if (StandardMaterial._AmbientTextureEnabled === value) {
  35682. return;
  35683. }
  35684. StandardMaterial._AmbientTextureEnabled = value;
  35685. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35686. },
  35687. enumerable: true,
  35688. configurable: true
  35689. });
  35690. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  35691. get: function () {
  35692. return StandardMaterial._OpacityTextureEnabled;
  35693. },
  35694. set: function (value) {
  35695. if (StandardMaterial._OpacityTextureEnabled === value) {
  35696. return;
  35697. }
  35698. StandardMaterial._OpacityTextureEnabled = value;
  35699. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35700. },
  35701. enumerable: true,
  35702. configurable: true
  35703. });
  35704. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  35705. get: function () {
  35706. return StandardMaterial._ReflectionTextureEnabled;
  35707. },
  35708. set: function (value) {
  35709. if (StandardMaterial._ReflectionTextureEnabled === value) {
  35710. return;
  35711. }
  35712. StandardMaterial._ReflectionTextureEnabled = value;
  35713. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35714. },
  35715. enumerable: true,
  35716. configurable: true
  35717. });
  35718. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  35719. get: function () {
  35720. return StandardMaterial._EmissiveTextureEnabled;
  35721. },
  35722. set: function (value) {
  35723. if (StandardMaterial._EmissiveTextureEnabled === value) {
  35724. return;
  35725. }
  35726. StandardMaterial._EmissiveTextureEnabled = value;
  35727. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35728. },
  35729. enumerable: true,
  35730. configurable: true
  35731. });
  35732. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  35733. get: function () {
  35734. return StandardMaterial._SpecularTextureEnabled;
  35735. },
  35736. set: function (value) {
  35737. if (StandardMaterial._SpecularTextureEnabled === value) {
  35738. return;
  35739. }
  35740. StandardMaterial._SpecularTextureEnabled = value;
  35741. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35742. },
  35743. enumerable: true,
  35744. configurable: true
  35745. });
  35746. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  35747. get: function () {
  35748. return StandardMaterial._BumpTextureEnabled;
  35749. },
  35750. set: function (value) {
  35751. if (StandardMaterial._BumpTextureEnabled === value) {
  35752. return;
  35753. }
  35754. StandardMaterial._BumpTextureEnabled = value;
  35755. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35756. },
  35757. enumerable: true,
  35758. configurable: true
  35759. });
  35760. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  35761. get: function () {
  35762. return StandardMaterial._LightmapTextureEnabled;
  35763. },
  35764. set: function (value) {
  35765. if (StandardMaterial._LightmapTextureEnabled === value) {
  35766. return;
  35767. }
  35768. StandardMaterial._LightmapTextureEnabled = value;
  35769. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35770. },
  35771. enumerable: true,
  35772. configurable: true
  35773. });
  35774. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  35775. get: function () {
  35776. return StandardMaterial._RefractionTextureEnabled;
  35777. },
  35778. set: function (value) {
  35779. if (StandardMaterial._RefractionTextureEnabled === value) {
  35780. return;
  35781. }
  35782. StandardMaterial._RefractionTextureEnabled = value;
  35783. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35784. },
  35785. enumerable: true,
  35786. configurable: true
  35787. });
  35788. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  35789. get: function () {
  35790. return StandardMaterial._ColorGradingTextureEnabled;
  35791. },
  35792. set: function (value) {
  35793. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  35794. return;
  35795. }
  35796. StandardMaterial._ColorGradingTextureEnabled = value;
  35797. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  35798. },
  35799. enumerable: true,
  35800. configurable: true
  35801. });
  35802. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  35803. get: function () {
  35804. return StandardMaterial._FresnelEnabled;
  35805. },
  35806. set: function (value) {
  35807. if (StandardMaterial._FresnelEnabled === value) {
  35808. return;
  35809. }
  35810. StandardMaterial._FresnelEnabled = value;
  35811. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  35812. },
  35813. enumerable: true,
  35814. configurable: true
  35815. });
  35816. // Flags used to enable or disable a type of texture for all Standard Materials
  35817. StandardMaterial._DiffuseTextureEnabled = true;
  35818. StandardMaterial._AmbientTextureEnabled = true;
  35819. StandardMaterial._OpacityTextureEnabled = true;
  35820. StandardMaterial._ReflectionTextureEnabled = true;
  35821. StandardMaterial._EmissiveTextureEnabled = true;
  35822. StandardMaterial._SpecularTextureEnabled = true;
  35823. StandardMaterial._BumpTextureEnabled = true;
  35824. StandardMaterial._LightmapTextureEnabled = true;
  35825. StandardMaterial._RefractionTextureEnabled = true;
  35826. StandardMaterial._ColorGradingTextureEnabled = true;
  35827. StandardMaterial._FresnelEnabled = true;
  35828. __decorate([
  35829. BABYLON.serializeAsTexture("diffuseTexture")
  35830. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  35831. __decorate([
  35832. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35833. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  35834. __decorate([
  35835. BABYLON.serializeAsTexture("ambientTexture")
  35836. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  35837. __decorate([
  35838. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35839. ], StandardMaterial.prototype, "ambientTexture", void 0);
  35840. __decorate([
  35841. BABYLON.serializeAsTexture("opacityTexture")
  35842. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  35843. __decorate([
  35844. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35845. ], StandardMaterial.prototype, "opacityTexture", void 0);
  35846. __decorate([
  35847. BABYLON.serializeAsTexture("reflectionTexture")
  35848. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  35849. __decorate([
  35850. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35851. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  35852. __decorate([
  35853. BABYLON.serializeAsTexture("emissiveTexture")
  35854. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  35855. __decorate([
  35856. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35857. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  35858. __decorate([
  35859. BABYLON.serializeAsTexture("specularTexture")
  35860. ], StandardMaterial.prototype, "_specularTexture", void 0);
  35861. __decorate([
  35862. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35863. ], StandardMaterial.prototype, "specularTexture", void 0);
  35864. __decorate([
  35865. BABYLON.serializeAsTexture("bumpTexture")
  35866. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  35867. __decorate([
  35868. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35869. ], StandardMaterial.prototype, "bumpTexture", void 0);
  35870. __decorate([
  35871. BABYLON.serializeAsTexture("lightmapTexture")
  35872. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  35873. __decorate([
  35874. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35875. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  35876. __decorate([
  35877. BABYLON.serializeAsTexture("refractionTexture")
  35878. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  35879. __decorate([
  35880. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35881. ], StandardMaterial.prototype, "refractionTexture", void 0);
  35882. __decorate([
  35883. BABYLON.serializeAsColor3("ambient")
  35884. ], StandardMaterial.prototype, "ambientColor", void 0);
  35885. __decorate([
  35886. BABYLON.serializeAsColor3("diffuse")
  35887. ], StandardMaterial.prototype, "diffuseColor", void 0);
  35888. __decorate([
  35889. BABYLON.serializeAsColor3("specular")
  35890. ], StandardMaterial.prototype, "specularColor", void 0);
  35891. __decorate([
  35892. BABYLON.serializeAsColor3("emissive")
  35893. ], StandardMaterial.prototype, "emissiveColor", void 0);
  35894. __decorate([
  35895. BABYLON.serialize()
  35896. ], StandardMaterial.prototype, "specularPower", void 0);
  35897. __decorate([
  35898. BABYLON.serialize("useAlphaFromDiffuseTexture")
  35899. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  35900. __decorate([
  35901. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35902. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  35903. __decorate([
  35904. BABYLON.serialize("useEmissiveAsIllumination")
  35905. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  35906. __decorate([
  35907. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35908. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  35909. __decorate([
  35910. BABYLON.serialize("linkEmissiveWithDiffuse")
  35911. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  35912. __decorate([
  35913. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35914. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  35915. __decorate([
  35916. BABYLON.serialize("useSpecularOverAlpha")
  35917. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  35918. __decorate([
  35919. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35920. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  35921. __decorate([
  35922. BABYLON.serialize("useReflectionOverAlpha")
  35923. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  35924. __decorate([
  35925. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35926. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  35927. __decorate([
  35928. BABYLON.serialize("disableLighting")
  35929. ], StandardMaterial.prototype, "_disableLighting", void 0);
  35930. __decorate([
  35931. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  35932. ], StandardMaterial.prototype, "disableLighting", void 0);
  35933. __decorate([
  35934. BABYLON.serialize("useParallax")
  35935. ], StandardMaterial.prototype, "_useParallax", void 0);
  35936. __decorate([
  35937. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35938. ], StandardMaterial.prototype, "useParallax", void 0);
  35939. __decorate([
  35940. BABYLON.serialize("useParallaxOcclusion")
  35941. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  35942. __decorate([
  35943. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35944. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  35945. __decorate([
  35946. BABYLON.serialize()
  35947. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  35948. __decorate([
  35949. BABYLON.serialize("roughness")
  35950. ], StandardMaterial.prototype, "_roughness", void 0);
  35951. __decorate([
  35952. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35953. ], StandardMaterial.prototype, "roughness", void 0);
  35954. __decorate([
  35955. BABYLON.serialize()
  35956. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  35957. __decorate([
  35958. BABYLON.serialize()
  35959. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  35960. __decorate([
  35961. BABYLON.serialize("useLightmapAsShadowmap")
  35962. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  35963. __decorate([
  35964. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  35965. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  35966. __decorate([
  35967. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  35968. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  35969. __decorate([
  35970. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  35971. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  35972. __decorate([
  35973. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  35974. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  35975. __decorate([
  35976. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  35977. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  35978. __decorate([
  35979. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  35980. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  35981. __decorate([
  35982. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  35983. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  35984. __decorate([
  35985. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  35986. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  35987. __decorate([
  35988. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  35989. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  35990. __decorate([
  35991. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  35992. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  35993. __decorate([
  35994. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  35995. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  35996. __decorate([
  35997. BABYLON.serialize("useReflectionFresnelFromSpecular")
  35998. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  35999. __decorate([
  36000. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  36001. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  36002. __decorate([
  36003. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  36004. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  36005. __decorate([
  36006. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36007. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  36008. __decorate([
  36009. BABYLON.serialize("maxSimultaneousLights")
  36010. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  36011. __decorate([
  36012. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  36013. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  36014. __decorate([
  36015. BABYLON.serialize("invertNormalMapX")
  36016. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  36017. __decorate([
  36018. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36019. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  36020. __decorate([
  36021. BABYLON.serialize("invertNormalMapY")
  36022. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  36023. __decorate([
  36024. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36025. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  36026. __decorate([
  36027. BABYLON.serialize("twoSidedLighting")
  36028. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  36029. __decorate([
  36030. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  36031. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  36032. __decorate([
  36033. BABYLON.serialize()
  36034. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  36035. return StandardMaterial;
  36036. }(BABYLON.PushMaterial));
  36037. BABYLON.StandardMaterial = StandardMaterial;
  36038. })(BABYLON || (BABYLON = {}));
  36039. //# sourceMappingURL=babylon.standardMaterial.js.map
  36040. var BABYLON;
  36041. (function (BABYLON) {
  36042. var PBRMaterialDefines = /** @class */ (function (_super) {
  36043. __extends(PBRMaterialDefines, _super);
  36044. function PBRMaterialDefines() {
  36045. var _this = _super.call(this) || this;
  36046. _this.PBR = true;
  36047. _this.MAINUV1 = false;
  36048. _this.MAINUV2 = false;
  36049. _this.UV1 = false;
  36050. _this.UV2 = false;
  36051. _this.ALBEDO = false;
  36052. _this.ALBEDODIRECTUV = 0;
  36053. _this.VERTEXCOLOR = false;
  36054. _this.AMBIENT = false;
  36055. _this.AMBIENTDIRECTUV = 0;
  36056. _this.AMBIENTINGRAYSCALE = false;
  36057. _this.OPACITY = false;
  36058. _this.VERTEXALPHA = false;
  36059. _this.OPACITYDIRECTUV = 0;
  36060. _this.OPACITYRGB = false;
  36061. _this.ALPHATEST = false;
  36062. _this.DEPTHPREPASS = false;
  36063. _this.ALPHABLEND = false;
  36064. _this.ALPHAFROMALBEDO = false;
  36065. _this.ALPHATESTVALUE = 0.5;
  36066. _this.SPECULAROVERALPHA = false;
  36067. _this.RADIANCEOVERALPHA = false;
  36068. _this.ALPHAFRESNEL = false;
  36069. _this.LINEARALPHAFRESNEL = false;
  36070. _this.PREMULTIPLYALPHA = false;
  36071. _this.EMISSIVE = false;
  36072. _this.EMISSIVEDIRECTUV = 0;
  36073. _this.REFLECTIVITY = false;
  36074. _this.REFLECTIVITYDIRECTUV = 0;
  36075. _this.SPECULARTERM = false;
  36076. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  36077. _this.MICROSURFACEAUTOMATIC = false;
  36078. _this.LODBASEDMICROSFURACE = false;
  36079. _this.MICROSURFACEMAP = false;
  36080. _this.MICROSURFACEMAPDIRECTUV = 0;
  36081. _this.METALLICWORKFLOW = false;
  36082. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  36083. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  36084. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  36085. _this.AOSTOREINMETALMAPRED = false;
  36086. _this.ENVIRONMENTBRDF = false;
  36087. _this.NORMAL = false;
  36088. _this.TANGENT = false;
  36089. _this.BUMP = false;
  36090. _this.BUMPDIRECTUV = 0;
  36091. _this.PARALLAX = false;
  36092. _this.PARALLAXOCCLUSION = false;
  36093. _this.NORMALXYSCALE = true;
  36094. _this.LIGHTMAP = false;
  36095. _this.LIGHTMAPDIRECTUV = 0;
  36096. _this.USELIGHTMAPASSHADOWMAP = false;
  36097. _this.REFLECTION = false;
  36098. _this.REFLECTIONMAP_3D = false;
  36099. _this.REFLECTIONMAP_SPHERICAL = false;
  36100. _this.REFLECTIONMAP_PLANAR = false;
  36101. _this.REFLECTIONMAP_CUBIC = false;
  36102. _this.REFLECTIONMAP_PROJECTION = false;
  36103. _this.REFLECTIONMAP_SKYBOX = false;
  36104. _this.REFLECTIONMAP_EXPLICIT = false;
  36105. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  36106. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  36107. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  36108. _this.INVERTCUBICMAP = false;
  36109. _this.USESPHERICALFROMREFLECTIONMAP = false;
  36110. _this.USESPHERICALINVERTEX = false;
  36111. _this.REFLECTIONMAP_OPPOSITEZ = false;
  36112. _this.LODINREFLECTIONALPHA = false;
  36113. _this.GAMMAREFLECTION = false;
  36114. _this.RADIANCEOCCLUSION = false;
  36115. _this.HORIZONOCCLUSION = false;
  36116. _this.REFRACTION = false;
  36117. _this.REFRACTIONMAP_3D = false;
  36118. _this.REFRACTIONMAP_OPPOSITEZ = false;
  36119. _this.LODINREFRACTIONALPHA = false;
  36120. _this.GAMMAREFRACTION = false;
  36121. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  36122. _this.INSTANCES = false;
  36123. _this.NUM_BONE_INFLUENCERS = 0;
  36124. _this.BonesPerMesh = 0;
  36125. _this.NONUNIFORMSCALING = false;
  36126. _this.MORPHTARGETS = false;
  36127. _this.MORPHTARGETS_NORMAL = false;
  36128. _this.MORPHTARGETS_TANGENT = false;
  36129. _this.NUM_MORPH_INFLUENCERS = 0;
  36130. _this.IMAGEPROCESSING = false;
  36131. _this.VIGNETTE = false;
  36132. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  36133. _this.VIGNETTEBLENDMODEOPAQUE = false;
  36134. _this.TONEMAPPING = false;
  36135. _this.CONTRAST = false;
  36136. _this.COLORCURVES = false;
  36137. _this.COLORGRADING = false;
  36138. _this.COLORGRADING3D = false;
  36139. _this.SAMPLER3DGREENDEPTH = false;
  36140. _this.SAMPLER3DBGRMAP = false;
  36141. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  36142. _this.EXPOSURE = false;
  36143. _this.USEPHYSICALLIGHTFALLOFF = false;
  36144. _this.TWOSIDEDLIGHTING = false;
  36145. _this.SHADOWFLOAT = false;
  36146. _this.CLIPPLANE = false;
  36147. _this.POINTSIZE = false;
  36148. _this.FOG = false;
  36149. _this.LOGARITHMICDEPTH = false;
  36150. _this.FORCENORMALFORWARD = false;
  36151. _this.rebuild();
  36152. return _this;
  36153. }
  36154. PBRMaterialDefines.prototype.reset = function () {
  36155. _super.prototype.reset.call(this);
  36156. this.ALPHATESTVALUE = 0.5;
  36157. this.PBR = true;
  36158. };
  36159. return PBRMaterialDefines;
  36160. }(BABYLON.MaterialDefines));
  36161. /**
  36162. * The Physically based material base class of BJS.
  36163. *
  36164. * This offers the main features of a standard PBR material.
  36165. * For more information, please refer to the documentation :
  36166. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  36167. */
  36168. var PBRBaseMaterial = /** @class */ (function (_super) {
  36169. __extends(PBRBaseMaterial, _super);
  36170. /**
  36171. * Instantiates a new PBRMaterial instance.
  36172. *
  36173. * @param name The material name
  36174. * @param scene The scene the material will be use in.
  36175. */
  36176. function PBRBaseMaterial(name, scene) {
  36177. var _this = _super.call(this, name, scene) || this;
  36178. /**
  36179. * Intensity of the direct lights e.g. the four lights available in your scene.
  36180. * This impacts both the direct diffuse and specular highlights.
  36181. */
  36182. _this._directIntensity = 1.0;
  36183. /**
  36184. * Intensity of the emissive part of the material.
  36185. * This helps controlling the emissive effect without modifying the emissive color.
  36186. */
  36187. _this._emissiveIntensity = 1.0;
  36188. /**
  36189. * Intensity of the environment e.g. how much the environment will light the object
  36190. * either through harmonics for rough material or through the refelction for shiny ones.
  36191. */
  36192. _this._environmentIntensity = 1.0;
  36193. /**
  36194. * This is a special control allowing the reduction of the specular highlights coming from the
  36195. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  36196. */
  36197. _this._specularIntensity = 1.0;
  36198. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  36199. /**
  36200. * Debug Control allowing disabling the bump map on this material.
  36201. */
  36202. _this._disableBumpMap = false;
  36203. /**
  36204. * AKA Occlusion Texture Intensity in other nomenclature.
  36205. */
  36206. _this._ambientTextureStrength = 1.0;
  36207. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  36208. /**
  36209. * AKA Diffuse Color in other nomenclature.
  36210. */
  36211. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  36212. /**
  36213. * AKA Specular Color in other nomenclature.
  36214. */
  36215. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  36216. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  36217. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  36218. /**
  36219. * AKA Glossiness in other nomenclature.
  36220. */
  36221. _this._microSurface = 0.9;
  36222. /**
  36223. * source material index of refraction (IOR)' / 'destination material IOR.
  36224. */
  36225. _this._indexOfRefraction = 0.66;
  36226. /**
  36227. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  36228. */
  36229. _this._invertRefractionY = false;
  36230. /**
  36231. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  36232. * Materials half opaque for instance using refraction could benefit from this control.
  36233. */
  36234. _this._linkRefractionWithTransparency = false;
  36235. _this._useLightmapAsShadowmap = false;
  36236. /**
  36237. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  36238. * makes the reflect vector face the model (under horizon).
  36239. */
  36240. _this._useHorizonOcclusion = true;
  36241. /**
  36242. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  36243. * too much the area relying on ambient texture to define their ambient occlusion.
  36244. */
  36245. _this._useRadianceOcclusion = true;
  36246. /**
  36247. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  36248. */
  36249. _this._useAlphaFromAlbedoTexture = false;
  36250. /**
  36251. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  36252. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  36253. */
  36254. _this._useSpecularOverAlpha = true;
  36255. /**
  36256. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  36257. */
  36258. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  36259. /**
  36260. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  36261. */
  36262. _this._useRoughnessFromMetallicTextureAlpha = true;
  36263. /**
  36264. * Specifies if the metallic texture contains the roughness information in its green channel.
  36265. */
  36266. _this._useRoughnessFromMetallicTextureGreen = false;
  36267. /**
  36268. * Specifies if the metallic texture contains the metallness information in its blue channel.
  36269. */
  36270. _this._useMetallnessFromMetallicTextureBlue = false;
  36271. /**
  36272. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  36273. */
  36274. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  36275. /**
  36276. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  36277. */
  36278. _this._useAmbientInGrayScale = false;
  36279. /**
  36280. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  36281. * The material will try to infer what glossiness each pixel should be.
  36282. */
  36283. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  36284. /**
  36285. * BJS is using an harcoded light falloff based on a manually sets up range.
  36286. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  36287. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  36288. */
  36289. _this._usePhysicalLightFalloff = true;
  36290. /**
  36291. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  36292. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  36293. */
  36294. _this._useRadianceOverAlpha = true;
  36295. /**
  36296. * Allows using the bump map in parallax mode.
  36297. */
  36298. _this._useParallax = false;
  36299. /**
  36300. * Allows using the bump map in parallax occlusion mode.
  36301. */
  36302. _this._useParallaxOcclusion = false;
  36303. /**
  36304. * Controls the scale bias of the parallax mode.
  36305. */
  36306. _this._parallaxScaleBias = 0.05;
  36307. /**
  36308. * If sets to true, disables all the lights affecting the material.
  36309. */
  36310. _this._disableLighting = false;
  36311. /**
  36312. * Number of Simultaneous lights allowed on the material.
  36313. */
  36314. _this._maxSimultaneousLights = 4;
  36315. /**
  36316. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  36317. */
  36318. _this._invertNormalMapX = false;
  36319. /**
  36320. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  36321. */
  36322. _this._invertNormalMapY = false;
  36323. /**
  36324. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  36325. */
  36326. _this._twoSidedLighting = false;
  36327. /**
  36328. * Defines the alpha limits in alpha test mode.
  36329. */
  36330. _this._alphaCutOff = 0.4;
  36331. /**
  36332. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  36333. */
  36334. _this._forceAlphaTest = false;
  36335. /**
  36336. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  36337. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  36338. */
  36339. _this._useAlphaFresnel = false;
  36340. /**
  36341. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  36342. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  36343. */
  36344. _this._useLinearAlphaFresnel = false;
  36345. /**
  36346. * The transparency mode of the material.
  36347. */
  36348. _this._transparencyMode = null;
  36349. /**
  36350. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  36351. * from cos thetav and roughness:
  36352. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  36353. */
  36354. _this._environmentBRDFTexture = null;
  36355. /**
  36356. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  36357. */
  36358. _this._forceIrradianceInFragment = false;
  36359. /**
  36360. * Force normal to face away from face.
  36361. */
  36362. _this._forceNormalForward = false;
  36363. _this._renderTargets = new BABYLON.SmartArray(16);
  36364. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  36365. // Setup the default processing configuration to the scene.
  36366. _this._attachImageProcessingConfiguration(null);
  36367. _this.getRenderTargetTextures = function () {
  36368. _this._renderTargets.reset();
  36369. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  36370. _this._renderTargets.push(_this._reflectionTexture);
  36371. }
  36372. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  36373. _this._renderTargets.push(_this._refractionTexture);
  36374. }
  36375. return _this._renderTargets;
  36376. };
  36377. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  36378. return _this;
  36379. }
  36380. /**
  36381. * Attaches a new image processing configuration to the PBR Material.
  36382. * @param configuration
  36383. */
  36384. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  36385. var _this = this;
  36386. if (configuration === this._imageProcessingConfiguration) {
  36387. return;
  36388. }
  36389. // Detaches observer.
  36390. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  36391. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  36392. }
  36393. // Pick the scene configuration if needed.
  36394. if (!configuration) {
  36395. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  36396. }
  36397. else {
  36398. this._imageProcessingConfiguration = configuration;
  36399. }
  36400. // Attaches observer.
  36401. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  36402. _this._markAllSubMeshesAsImageProcessingDirty();
  36403. });
  36404. };
  36405. PBRBaseMaterial.prototype.getClassName = function () {
  36406. return "PBRBaseMaterial";
  36407. };
  36408. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  36409. get: function () {
  36410. return this._useLogarithmicDepth;
  36411. },
  36412. set: function (value) {
  36413. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  36414. },
  36415. enumerable: true,
  36416. configurable: true
  36417. });
  36418. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  36419. /**
  36420. * Gets the current transparency mode.
  36421. */
  36422. get: function () {
  36423. return this._transparencyMode;
  36424. },
  36425. /**
  36426. * Sets the transparency mode of the material.
  36427. */
  36428. set: function (value) {
  36429. if (this._transparencyMode === value) {
  36430. return;
  36431. }
  36432. this._transparencyMode = value;
  36433. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  36434. this._markAllSubMeshesAsTexturesDirty();
  36435. },
  36436. enumerable: true,
  36437. configurable: true
  36438. });
  36439. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  36440. /**
  36441. * Returns true if alpha blending should be disabled.
  36442. */
  36443. get: function () {
  36444. return (this._linkRefractionWithTransparency ||
  36445. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  36446. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  36447. },
  36448. enumerable: true,
  36449. configurable: true
  36450. });
  36451. /**
  36452. * Specifies whether or not this material should be rendered in alpha blend mode.
  36453. */
  36454. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  36455. if (this._disableAlphaBlending) {
  36456. return false;
  36457. }
  36458. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  36459. };
  36460. /**
  36461. * Specifies whether or not this material should be rendered in alpha blend mode for the given mesh.
  36462. */
  36463. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  36464. if (this._disableAlphaBlending) {
  36465. return false;
  36466. }
  36467. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  36468. };
  36469. /**
  36470. * Specifies whether or not this material should be rendered in alpha test mode.
  36471. */
  36472. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  36473. if (this._forceAlphaTest) {
  36474. return true;
  36475. }
  36476. if (this._linkRefractionWithTransparency) {
  36477. return false;
  36478. }
  36479. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  36480. };
  36481. /**
  36482. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  36483. */
  36484. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  36485. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  36486. };
  36487. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  36488. return this._albedoTexture;
  36489. };
  36490. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  36491. var _this = this;
  36492. if (subMesh.effect && this.isFrozen) {
  36493. if (this._wasPreviouslyReady) {
  36494. return true;
  36495. }
  36496. }
  36497. if (!subMesh._materialDefines) {
  36498. subMesh._materialDefines = new PBRMaterialDefines();
  36499. }
  36500. var scene = this.getScene();
  36501. var defines = subMesh._materialDefines;
  36502. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  36503. if (defines._renderId === scene.getRenderId()) {
  36504. return true;
  36505. }
  36506. }
  36507. var engine = scene.getEngine();
  36508. // Lights
  36509. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  36510. defines._needNormals = true;
  36511. // Textures
  36512. if (defines._areTexturesDirty) {
  36513. defines._needUVs = false;
  36514. if (scene.texturesEnabled) {
  36515. if (scene.getEngine().getCaps().textureLOD) {
  36516. defines.LODBASEDMICROSFURACE = true;
  36517. }
  36518. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  36519. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  36520. return false;
  36521. }
  36522. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  36523. }
  36524. else {
  36525. defines.ALBEDO = false;
  36526. }
  36527. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  36528. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  36529. return false;
  36530. }
  36531. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  36532. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  36533. }
  36534. else {
  36535. defines.AMBIENT = false;
  36536. }
  36537. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  36538. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  36539. return false;
  36540. }
  36541. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  36542. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  36543. }
  36544. else {
  36545. defines.OPACITY = false;
  36546. }
  36547. var reflectionTexture = this._getReflectionTexture();
  36548. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  36549. if (!reflectionTexture.isReadyOrNotBlocking()) {
  36550. return false;
  36551. }
  36552. defines.REFLECTION = true;
  36553. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  36554. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  36555. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  36556. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  36557. defines.INVERTCUBICMAP = true;
  36558. }
  36559. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  36560. switch (reflectionTexture.coordinatesMode) {
  36561. case BABYLON.Texture.CUBIC_MODE:
  36562. case BABYLON.Texture.INVCUBIC_MODE:
  36563. defines.REFLECTIONMAP_CUBIC = true;
  36564. break;
  36565. case BABYLON.Texture.EXPLICIT_MODE:
  36566. defines.REFLECTIONMAP_EXPLICIT = true;
  36567. break;
  36568. case BABYLON.Texture.PLANAR_MODE:
  36569. defines.REFLECTIONMAP_PLANAR = true;
  36570. break;
  36571. case BABYLON.Texture.PROJECTION_MODE:
  36572. defines.REFLECTIONMAP_PROJECTION = true;
  36573. break;
  36574. case BABYLON.Texture.SKYBOX_MODE:
  36575. defines.REFLECTIONMAP_SKYBOX = true;
  36576. break;
  36577. case BABYLON.Texture.SPHERICAL_MODE:
  36578. defines.REFLECTIONMAP_SPHERICAL = true;
  36579. break;
  36580. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  36581. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  36582. break;
  36583. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  36584. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  36585. break;
  36586. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  36587. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  36588. break;
  36589. }
  36590. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  36591. if (reflectionTexture.sphericalPolynomial) {
  36592. defines.USESPHERICALFROMREFLECTIONMAP = true;
  36593. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  36594. defines.USESPHERICALINVERTEX = false;
  36595. }
  36596. else {
  36597. defines.USESPHERICALINVERTEX = true;
  36598. }
  36599. }
  36600. }
  36601. }
  36602. else {
  36603. defines.REFLECTION = false;
  36604. defines.REFLECTIONMAP_3D = false;
  36605. defines.REFLECTIONMAP_SPHERICAL = false;
  36606. defines.REFLECTIONMAP_PLANAR = false;
  36607. defines.REFLECTIONMAP_CUBIC = false;
  36608. defines.REFLECTIONMAP_PROJECTION = false;
  36609. defines.REFLECTIONMAP_SKYBOX = false;
  36610. defines.REFLECTIONMAP_EXPLICIT = false;
  36611. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  36612. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  36613. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  36614. defines.INVERTCUBICMAP = false;
  36615. defines.USESPHERICALFROMREFLECTIONMAP = false;
  36616. defines.USESPHERICALINVERTEX = false;
  36617. defines.REFLECTIONMAP_OPPOSITEZ = false;
  36618. defines.LODINREFLECTIONALPHA = false;
  36619. defines.GAMMAREFLECTION = false;
  36620. }
  36621. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  36622. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  36623. return false;
  36624. }
  36625. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  36626. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  36627. }
  36628. else {
  36629. defines.LIGHTMAP = false;
  36630. }
  36631. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  36632. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  36633. return false;
  36634. }
  36635. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  36636. }
  36637. else {
  36638. defines.EMISSIVE = false;
  36639. }
  36640. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  36641. if (this._metallicTexture) {
  36642. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  36643. return false;
  36644. }
  36645. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  36646. defines.METALLICWORKFLOW = true;
  36647. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  36648. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  36649. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  36650. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  36651. }
  36652. else if (this._reflectivityTexture) {
  36653. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  36654. return false;
  36655. }
  36656. defines.METALLICWORKFLOW = false;
  36657. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  36658. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  36659. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  36660. }
  36661. else {
  36662. defines.METALLICWORKFLOW = false;
  36663. defines.REFLECTIVITY = false;
  36664. }
  36665. if (this._microSurfaceTexture) {
  36666. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  36667. return false;
  36668. }
  36669. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  36670. }
  36671. else {
  36672. defines.MICROSURFACEMAP = false;
  36673. }
  36674. }
  36675. else {
  36676. defines.REFLECTIVITY = false;
  36677. defines.MICROSURFACEMAP = false;
  36678. }
  36679. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  36680. // Bump texure can not be none blocking.
  36681. if (!this._bumpTexture.isReady()) {
  36682. return false;
  36683. }
  36684. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  36685. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  36686. defines.PARALLAX = true;
  36687. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  36688. }
  36689. else {
  36690. defines.PARALLAX = false;
  36691. }
  36692. }
  36693. else {
  36694. defines.BUMP = false;
  36695. }
  36696. var refractionTexture = this._getRefractionTexture();
  36697. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  36698. if (!refractionTexture.isReadyOrNotBlocking()) {
  36699. return false;
  36700. }
  36701. defines.REFRACTION = true;
  36702. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  36703. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  36704. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  36705. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  36706. if (this._linkRefractionWithTransparency) {
  36707. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  36708. }
  36709. }
  36710. else {
  36711. defines.REFRACTION = false;
  36712. }
  36713. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  36714. // This is blocking.
  36715. if (!this._environmentBRDFTexture.isReady()) {
  36716. return false;
  36717. }
  36718. defines.ENVIRONMENTBRDF = true;
  36719. }
  36720. else {
  36721. defines.ENVIRONMENTBRDF = false;
  36722. }
  36723. if (this._shouldUseAlphaFromAlbedoTexture()) {
  36724. defines.ALPHAFROMALBEDO = true;
  36725. }
  36726. else {
  36727. defines.ALPHAFROMALBEDO = false;
  36728. }
  36729. }
  36730. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  36731. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  36732. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  36733. if ((this._metallic !== undefined && this._metallic !== null) || (this._roughness !== undefined && this._roughness !== null)) {
  36734. defines.METALLICWORKFLOW = true;
  36735. }
  36736. else {
  36737. defines.METALLICWORKFLOW = false;
  36738. }
  36739. if (!this.backFaceCulling && this._twoSidedLighting) {
  36740. defines.TWOSIDEDLIGHTING = true;
  36741. }
  36742. else {
  36743. defines.TWOSIDEDLIGHTING = false;
  36744. }
  36745. defines.ALPHATESTVALUE = this._alphaCutOff;
  36746. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  36747. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  36748. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  36749. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  36750. }
  36751. if (defines._areImageProcessingDirty) {
  36752. if (!this._imageProcessingConfiguration.isReady()) {
  36753. return false;
  36754. }
  36755. this._imageProcessingConfiguration.prepareDefines(defines);
  36756. }
  36757. defines.FORCENORMALFORWARD = this._forceNormalForward;
  36758. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  36759. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  36760. // Misc.
  36761. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  36762. // Values that need to be evaluated on every frame
  36763. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, this._forceAlphaTest);
  36764. // Attribs
  36765. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE) && mesh) {
  36766. var bufferMesh = null;
  36767. if (mesh instanceof BABYLON.InstancedMesh) {
  36768. bufferMesh = mesh.sourceMesh;
  36769. }
  36770. else if (mesh instanceof BABYLON.Mesh) {
  36771. bufferMesh = mesh;
  36772. }
  36773. if (bufferMesh) {
  36774. if (bufferMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  36775. // If the first normal's components is the zero vector in one of the submeshes, we have invalid normals
  36776. var normalVertexBuffer = bufferMesh.getVertexBuffer(BABYLON.VertexBuffer.NormalKind);
  36777. var normals = normalVertexBuffer.getData();
  36778. var vertexBufferOffset = normalVertexBuffer.getOffset();
  36779. var strideSize = normalVertexBuffer.getStrideSize();
  36780. var offset = vertexBufferOffset + subMesh.indexStart * strideSize;
  36781. if (normals[offset] === 0 && normals[offset + 1] === 0 && normals[offset + 2] === 0) {
  36782. defines.NORMAL = false;
  36783. }
  36784. if (bufferMesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  36785. // If the first tangent's components is the zero vector in one of the submeshes, we have invalid tangents
  36786. var tangentVertexBuffer = bufferMesh.getVertexBuffer(BABYLON.VertexBuffer.TangentKind);
  36787. var tangents = tangentVertexBuffer.getData();
  36788. var vertexBufferOffset_1 = tangentVertexBuffer.getOffset();
  36789. var strideSize_1 = tangentVertexBuffer.getStrideSize();
  36790. var offset_1 = vertexBufferOffset_1 + subMesh.indexStart * strideSize_1;
  36791. if (tangents[offset_1] === 0 && tangents[offset_1 + 1] === 0 && tangents[offset_1 + 2] === 0) {
  36792. defines.TANGENT = false;
  36793. }
  36794. }
  36795. }
  36796. else {
  36797. if (!scene.getEngine().getCaps().standardDerivatives) {
  36798. bufferMesh.createNormals(true);
  36799. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + bufferMesh.name);
  36800. }
  36801. }
  36802. }
  36803. }
  36804. // Get correct effect
  36805. if (defines.isDirty) {
  36806. defines.markAsProcessed();
  36807. scene.resetCachedMaterial();
  36808. // Fallbacks
  36809. var fallbacks = new BABYLON.EffectFallbacks();
  36810. var fallbackRank = 0;
  36811. if (defines.USESPHERICALINVERTEX) {
  36812. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  36813. }
  36814. if (defines.FOG) {
  36815. fallbacks.addFallback(fallbackRank, "FOG");
  36816. }
  36817. if (defines.POINTSIZE) {
  36818. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  36819. }
  36820. if (defines.LOGARITHMICDEPTH) {
  36821. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  36822. }
  36823. if (defines.PARALLAX) {
  36824. fallbacks.addFallback(fallbackRank, "PARALLAX");
  36825. }
  36826. if (defines.PARALLAXOCCLUSION) {
  36827. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  36828. }
  36829. if (defines.ENVIRONMENTBRDF) {
  36830. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  36831. }
  36832. if (defines.TANGENT) {
  36833. fallbacks.addFallback(fallbackRank++, "TANGENT");
  36834. }
  36835. if (defines.BUMP) {
  36836. fallbacks.addFallback(fallbackRank++, "BUMP");
  36837. }
  36838. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  36839. if (defines.SPECULARTERM) {
  36840. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  36841. }
  36842. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  36843. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  36844. }
  36845. if (defines.LIGHTMAP) {
  36846. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  36847. }
  36848. if (defines.NORMAL) {
  36849. fallbacks.addFallback(fallbackRank++, "NORMAL");
  36850. }
  36851. if (defines.AMBIENT) {
  36852. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  36853. }
  36854. if (defines.EMISSIVE) {
  36855. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  36856. }
  36857. if (defines.VERTEXCOLOR) {
  36858. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  36859. }
  36860. if (defines.NUM_BONE_INFLUENCERS > 0) {
  36861. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  36862. }
  36863. if (defines.MORPHTARGETS) {
  36864. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  36865. }
  36866. //Attributes
  36867. var attribs = [BABYLON.VertexBuffer.PositionKind];
  36868. if (defines.NORMAL) {
  36869. attribs.push(BABYLON.VertexBuffer.NormalKind);
  36870. }
  36871. if (defines.TANGENT) {
  36872. attribs.push(BABYLON.VertexBuffer.TangentKind);
  36873. }
  36874. if (defines.UV1) {
  36875. attribs.push(BABYLON.VertexBuffer.UVKind);
  36876. }
  36877. if (defines.UV2) {
  36878. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  36879. }
  36880. if (defines.VERTEXCOLOR) {
  36881. attribs.push(BABYLON.VertexBuffer.ColorKind);
  36882. }
  36883. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  36884. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  36885. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  36886. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  36887. "vFogInfos", "vFogColor", "pointSize",
  36888. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  36889. "mBones",
  36890. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  36891. "vLightingIntensity",
  36892. "logarithmicDepthConstant",
  36893. "vSphericalX", "vSphericalY", "vSphericalZ",
  36894. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  36895. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  36896. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  36897. "vTangentSpaceParams"
  36898. ];
  36899. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  36900. "bumpSampler", "lightmapSampler", "opacitySampler",
  36901. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  36902. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  36903. "microSurfaceSampler", "environmentBrdfSampler"];
  36904. var uniformBuffers = ["Material", "Scene"];
  36905. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  36906. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  36907. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  36908. uniformsNames: uniforms,
  36909. uniformBuffersNames: uniformBuffers,
  36910. samplers: samplers,
  36911. defines: defines,
  36912. maxSimultaneousLights: this._maxSimultaneousLights
  36913. });
  36914. var onCompiled = function (effect) {
  36915. if (_this.onCompiled) {
  36916. _this.onCompiled(effect);
  36917. }
  36918. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  36919. };
  36920. var join = defines.toString();
  36921. subMesh.setEffect(scene.getEngine().createEffect("pbr", {
  36922. attributes: attribs,
  36923. uniformsNames: uniforms,
  36924. uniformBuffersNames: uniformBuffers,
  36925. samplers: samplers,
  36926. defines: join,
  36927. fallbacks: fallbacks,
  36928. onCompiled: onCompiled,
  36929. onError: this.onError,
  36930. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  36931. }, engine), defines);
  36932. this.buildUniformLayout();
  36933. }
  36934. if (!subMesh.effect || !subMesh.effect.isReady()) {
  36935. return false;
  36936. }
  36937. defines._renderId = scene.getRenderId();
  36938. this._wasPreviouslyReady = true;
  36939. return true;
  36940. };
  36941. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  36942. // Order is important !
  36943. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  36944. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  36945. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  36946. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  36947. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  36948. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  36949. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  36950. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  36951. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  36952. this._uniformBuffer.addUniform("vBumpInfos", 3);
  36953. this._uniformBuffer.addUniform("albedoMatrix", 16);
  36954. this._uniformBuffer.addUniform("ambientMatrix", 16);
  36955. this._uniformBuffer.addUniform("opacityMatrix", 16);
  36956. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  36957. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  36958. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  36959. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  36960. this._uniformBuffer.addUniform("bumpMatrix", 16);
  36961. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  36962. this._uniformBuffer.addUniform("refractionMatrix", 16);
  36963. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  36964. this._uniformBuffer.addUniform("vReflectionColor", 3);
  36965. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  36966. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  36967. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  36968. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  36969. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  36970. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  36971. this._uniformBuffer.addUniform("pointSize", 1);
  36972. this._uniformBuffer.create();
  36973. };
  36974. PBRBaseMaterial.prototype.unbind = function () {
  36975. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  36976. this._uniformBuffer.setTexture("reflectionSampler", null);
  36977. }
  36978. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  36979. this._uniformBuffer.setTexture("refractionSampler", null);
  36980. }
  36981. _super.prototype.unbind.call(this);
  36982. };
  36983. PBRBaseMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  36984. this._activeEffect.setMatrix("world", world);
  36985. };
  36986. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  36987. var scene = this.getScene();
  36988. var defines = subMesh._materialDefines;
  36989. if (!defines) {
  36990. return;
  36991. }
  36992. var effect = subMesh.effect;
  36993. if (!effect) {
  36994. return;
  36995. }
  36996. this._activeEffect = effect;
  36997. // Matrices
  36998. this.bindOnlyWorldMatrix(world);
  36999. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  37000. // Bones
  37001. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  37002. var reflectionTexture = null;
  37003. if (mustRebind) {
  37004. this._uniformBuffer.bindToEffect(effect, "Material");
  37005. this.bindViewProjection(effect);
  37006. reflectionTexture = this._getReflectionTexture();
  37007. var refractionTexture = this._getRefractionTexture();
  37008. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  37009. // Texture uniforms
  37010. if (scene.texturesEnabled) {
  37011. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  37012. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  37013. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  37014. }
  37015. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  37016. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  37017. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  37018. }
  37019. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  37020. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  37021. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  37022. }
  37023. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  37024. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  37025. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  37026. var polynomials = reflectionTexture.sphericalPolynomial;
  37027. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  37028. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  37029. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  37030. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  37031. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  37032. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  37033. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  37034. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  37035. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  37036. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  37037. }
  37038. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  37039. }
  37040. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  37041. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  37042. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  37043. }
  37044. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  37045. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  37046. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  37047. }
  37048. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  37049. if (this._metallicTexture) {
  37050. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  37051. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  37052. }
  37053. else if (this._reflectivityTexture) {
  37054. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  37055. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  37056. }
  37057. if (this._microSurfaceTexture) {
  37058. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  37059. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  37060. }
  37061. }
  37062. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  37063. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  37064. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  37065. if (scene._mirroredCameraPosition) {
  37066. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  37067. }
  37068. else {
  37069. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  37070. }
  37071. }
  37072. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  37073. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  37074. var depth = 1.0;
  37075. if (!refractionTexture.isCube) {
  37076. if (refractionTexture.depth) {
  37077. depth = refractionTexture.depth;
  37078. }
  37079. }
  37080. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  37081. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  37082. }
  37083. }
  37084. // Point size
  37085. if (this.pointsCloud) {
  37086. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  37087. }
  37088. // Colors
  37089. if (defines.METALLICWORKFLOW) {
  37090. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  37091. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  37092. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  37093. }
  37094. else {
  37095. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  37096. }
  37097. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  37098. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  37099. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  37100. // Misc
  37101. this._lightingInfos.x = this._directIntensity;
  37102. this._lightingInfos.y = this._emissiveIntensity;
  37103. this._lightingInfos.z = this._environmentIntensity;
  37104. this._lightingInfos.w = this._specularIntensity;
  37105. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  37106. }
  37107. // Textures
  37108. if (scene.texturesEnabled) {
  37109. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  37110. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  37111. }
  37112. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  37113. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  37114. }
  37115. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  37116. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  37117. }
  37118. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  37119. if (defines.LODBASEDMICROSFURACE) {
  37120. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  37121. }
  37122. else {
  37123. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  37124. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  37125. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  37126. }
  37127. }
  37128. if (defines.ENVIRONMENTBRDF) {
  37129. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  37130. }
  37131. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  37132. if (defines.LODBASEDMICROSFURACE) {
  37133. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  37134. }
  37135. else {
  37136. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  37137. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  37138. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  37139. }
  37140. }
  37141. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  37142. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  37143. }
  37144. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  37145. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  37146. }
  37147. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  37148. if (this._metallicTexture) {
  37149. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  37150. }
  37151. else if (this._reflectivityTexture) {
  37152. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  37153. }
  37154. if (this._microSurfaceTexture) {
  37155. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  37156. }
  37157. }
  37158. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  37159. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  37160. }
  37161. }
  37162. // Clip plane
  37163. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  37164. // Colors
  37165. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  37166. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  37167. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  37168. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  37169. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  37170. }
  37171. if (mustRebind || !this.isFrozen) {
  37172. // Lights
  37173. if (scene.lightsEnabled && !this._disableLighting) {
  37174. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  37175. }
  37176. // View
  37177. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  37178. this.bindView(effect);
  37179. }
  37180. // Fog
  37181. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  37182. // Morph targets
  37183. if (defines.NUM_MORPH_INFLUENCERS) {
  37184. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  37185. }
  37186. // image processing
  37187. this._imageProcessingConfiguration.bind(this._activeEffect);
  37188. // Log. depth
  37189. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  37190. }
  37191. this._uniformBuffer.update();
  37192. this._afterBind(mesh);
  37193. };
  37194. PBRBaseMaterial.prototype.getAnimatables = function () {
  37195. var results = [];
  37196. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  37197. results.push(this._albedoTexture);
  37198. }
  37199. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  37200. results.push(this._ambientTexture);
  37201. }
  37202. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  37203. results.push(this._opacityTexture);
  37204. }
  37205. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  37206. results.push(this._reflectionTexture);
  37207. }
  37208. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  37209. results.push(this._emissiveTexture);
  37210. }
  37211. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  37212. results.push(this._metallicTexture);
  37213. }
  37214. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  37215. results.push(this._reflectivityTexture);
  37216. }
  37217. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  37218. results.push(this._bumpTexture);
  37219. }
  37220. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  37221. results.push(this._lightmapTexture);
  37222. }
  37223. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  37224. results.push(this._refractionTexture);
  37225. }
  37226. return results;
  37227. };
  37228. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  37229. if (this._reflectionTexture) {
  37230. return this._reflectionTexture;
  37231. }
  37232. return this.getScene().environmentTexture;
  37233. };
  37234. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  37235. if (this._refractionTexture) {
  37236. return this._refractionTexture;
  37237. }
  37238. if (this._linkRefractionWithTransparency) {
  37239. return this.getScene().environmentTexture;
  37240. }
  37241. return null;
  37242. };
  37243. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  37244. if (forceDisposeTextures) {
  37245. if (this._albedoTexture) {
  37246. this._albedoTexture.dispose();
  37247. }
  37248. if (this._ambientTexture) {
  37249. this._ambientTexture.dispose();
  37250. }
  37251. if (this._opacityTexture) {
  37252. this._opacityTexture.dispose();
  37253. }
  37254. if (this._reflectionTexture) {
  37255. this._reflectionTexture.dispose();
  37256. }
  37257. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  37258. this._environmentBRDFTexture.dispose();
  37259. }
  37260. if (this._emissiveTexture) {
  37261. this._emissiveTexture.dispose();
  37262. }
  37263. if (this._metallicTexture) {
  37264. this._metallicTexture.dispose();
  37265. }
  37266. if (this._reflectivityTexture) {
  37267. this._reflectivityTexture.dispose();
  37268. }
  37269. if (this._bumpTexture) {
  37270. this._bumpTexture.dispose();
  37271. }
  37272. if (this._lightmapTexture) {
  37273. this._lightmapTexture.dispose();
  37274. }
  37275. if (this._refractionTexture) {
  37276. this._refractionTexture.dispose();
  37277. }
  37278. }
  37279. this._renderTargets.dispose();
  37280. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  37281. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  37282. }
  37283. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  37284. };
  37285. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  37286. __decorate([
  37287. BABYLON.serializeAsImageProcessingConfiguration()
  37288. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  37289. __decorate([
  37290. BABYLON.serialize()
  37291. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  37292. __decorate([
  37293. BABYLON.serialize()
  37294. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  37295. return PBRBaseMaterial;
  37296. }(BABYLON.PushMaterial));
  37297. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  37298. })(BABYLON || (BABYLON = {}));
  37299. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  37300. var BABYLON;
  37301. (function (BABYLON) {
  37302. var Internals;
  37303. (function (Internals) {
  37304. /**
  37305. * The Physically based simple base material of BJS.
  37306. *
  37307. * This enables better naming and convention enforcements on top of the pbrMaterial.
  37308. * It is used as the base class for both the specGloss and metalRough conventions.
  37309. */
  37310. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  37311. __extends(PBRBaseSimpleMaterial, _super);
  37312. /**
  37313. * Instantiates a new PBRMaterial instance.
  37314. *
  37315. * @param name The material name
  37316. * @param scene The scene the material will be use in.
  37317. */
  37318. function PBRBaseSimpleMaterial(name, scene) {
  37319. var _this = _super.call(this, name, scene) || this;
  37320. /**
  37321. * Number of Simultaneous lights allowed on the material.
  37322. */
  37323. _this.maxSimultaneousLights = 4;
  37324. /**
  37325. * If sets to true, disables all the lights affecting the material.
  37326. */
  37327. _this.disableLighting = false;
  37328. /**
  37329. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  37330. */
  37331. _this.invertNormalMapX = false;
  37332. /**
  37333. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  37334. */
  37335. _this.invertNormalMapY = false;
  37336. /**
  37337. * Emissivie color used to self-illuminate the model.
  37338. */
  37339. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  37340. /**
  37341. * Occlusion Channel Strenght.
  37342. */
  37343. _this.occlusionStrength = 1.0;
  37344. _this.useLightmapAsShadowmap = false;
  37345. _this._useAlphaFromAlbedoTexture = true;
  37346. _this._useAmbientInGrayScale = true;
  37347. return _this;
  37348. }
  37349. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  37350. /**
  37351. * Gets the current double sided mode.
  37352. */
  37353. get: function () {
  37354. return this._twoSidedLighting;
  37355. },
  37356. /**
  37357. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  37358. */
  37359. set: function (value) {
  37360. if (this._twoSidedLighting === value) {
  37361. return;
  37362. }
  37363. this._twoSidedLighting = value;
  37364. this.backFaceCulling = !value;
  37365. this._markAllSubMeshesAsTexturesDirty();
  37366. },
  37367. enumerable: true,
  37368. configurable: true
  37369. });
  37370. /**
  37371. * Return the active textures of the material.
  37372. */
  37373. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  37374. var activeTextures = _super.prototype.getActiveTextures.call(this);
  37375. if (this.environmentTexture) {
  37376. activeTextures.push(this.environmentTexture);
  37377. }
  37378. if (this.normalTexture) {
  37379. activeTextures.push(this.normalTexture);
  37380. }
  37381. if (this.emissiveTexture) {
  37382. activeTextures.push(this.emissiveTexture);
  37383. }
  37384. if (this.occlusionTexture) {
  37385. activeTextures.push(this.occlusionTexture);
  37386. }
  37387. if (this.lightmapTexture) {
  37388. activeTextures.push(this.lightmapTexture);
  37389. }
  37390. return activeTextures;
  37391. };
  37392. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  37393. if (_super.prototype.hasTexture.call(this, texture)) {
  37394. return true;
  37395. }
  37396. if (this.lightmapTexture === texture) {
  37397. return true;
  37398. }
  37399. return false;
  37400. };
  37401. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  37402. return "PBRBaseSimpleMaterial";
  37403. };
  37404. __decorate([
  37405. BABYLON.serialize(),
  37406. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  37407. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  37408. __decorate([
  37409. BABYLON.serialize(),
  37410. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  37411. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  37412. __decorate([
  37413. BABYLON.serializeAsTexture(),
  37414. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  37415. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  37416. __decorate([
  37417. BABYLON.serialize(),
  37418. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37419. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  37420. __decorate([
  37421. BABYLON.serialize(),
  37422. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37423. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  37424. __decorate([
  37425. BABYLON.serializeAsTexture(),
  37426. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  37427. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  37428. __decorate([
  37429. BABYLON.serializeAsColor3("emissive"),
  37430. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37431. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  37432. __decorate([
  37433. BABYLON.serializeAsTexture(),
  37434. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37435. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  37436. __decorate([
  37437. BABYLON.serialize(),
  37438. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  37439. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  37440. __decorate([
  37441. BABYLON.serializeAsTexture(),
  37442. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  37443. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  37444. __decorate([
  37445. BABYLON.serialize(),
  37446. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  37447. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  37448. __decorate([
  37449. BABYLON.serialize()
  37450. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  37451. __decorate([
  37452. BABYLON.serializeAsTexture(),
  37453. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  37454. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  37455. __decorate([
  37456. BABYLON.serialize(),
  37457. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37458. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  37459. return PBRBaseSimpleMaterial;
  37460. }(BABYLON.PBRBaseMaterial));
  37461. Internals.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  37462. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  37463. })(BABYLON || (BABYLON = {}));
  37464. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  37465. var BABYLON;
  37466. (function (BABYLON) {
  37467. /**
  37468. * The Physically based material of BJS.
  37469. *
  37470. * This offers the main features of a standard PBR material.
  37471. * For more information, please refer to the documentation :
  37472. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  37473. */
  37474. var PBRMaterial = /** @class */ (function (_super) {
  37475. __extends(PBRMaterial, _super);
  37476. /**
  37477. * Instantiates a new PBRMaterial instance.
  37478. *
  37479. * @param name The material name
  37480. * @param scene The scene the material will be use in.
  37481. */
  37482. function PBRMaterial(name, scene) {
  37483. var _this = _super.call(this, name, scene) || this;
  37484. /**
  37485. * Intensity of the direct lights e.g. the four lights available in your scene.
  37486. * This impacts both the direct diffuse and specular highlights.
  37487. */
  37488. _this.directIntensity = 1.0;
  37489. /**
  37490. * Intensity of the emissive part of the material.
  37491. * This helps controlling the emissive effect without modifying the emissive color.
  37492. */
  37493. _this.emissiveIntensity = 1.0;
  37494. /**
  37495. * Intensity of the environment e.g. how much the environment will light the object
  37496. * either through harmonics for rough material or through the refelction for shiny ones.
  37497. */
  37498. _this.environmentIntensity = 1.0;
  37499. /**
  37500. * This is a special control allowing the reduction of the specular highlights coming from the
  37501. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  37502. */
  37503. _this.specularIntensity = 1.0;
  37504. /**
  37505. * Debug Control allowing disabling the bump map on this material.
  37506. */
  37507. _this.disableBumpMap = false;
  37508. /**
  37509. * AKA Occlusion Texture Intensity in other nomenclature.
  37510. */
  37511. _this.ambientTextureStrength = 1.0;
  37512. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  37513. /**
  37514. * AKA Diffuse Color in other nomenclature.
  37515. */
  37516. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  37517. /**
  37518. * AKA Specular Color in other nomenclature.
  37519. */
  37520. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  37521. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  37522. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  37523. /**
  37524. * AKA Glossiness in other nomenclature.
  37525. */
  37526. _this.microSurface = 1.0;
  37527. /**
  37528. * source material index of refraction (IOR)' / 'destination material IOR.
  37529. */
  37530. _this.indexOfRefraction = 0.66;
  37531. /**
  37532. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  37533. */
  37534. _this.invertRefractionY = false;
  37535. /**
  37536. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  37537. * Materials half opaque for instance using refraction could benefit from this control.
  37538. */
  37539. _this.linkRefractionWithTransparency = false;
  37540. _this.useLightmapAsShadowmap = false;
  37541. /**
  37542. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  37543. */
  37544. _this.useAlphaFromAlbedoTexture = false;
  37545. /**
  37546. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  37547. */
  37548. _this.forceAlphaTest = false;
  37549. /**
  37550. * Defines the alpha limits in alpha test mode.
  37551. */
  37552. _this.alphaCutOff = 0.4;
  37553. /**
  37554. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  37555. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  37556. */
  37557. _this.useSpecularOverAlpha = true;
  37558. /**
  37559. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  37560. */
  37561. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  37562. /**
  37563. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  37564. */
  37565. _this.useRoughnessFromMetallicTextureAlpha = true;
  37566. /**
  37567. * Specifies if the metallic texture contains the roughness information in its green channel.
  37568. */
  37569. _this.useRoughnessFromMetallicTextureGreen = false;
  37570. /**
  37571. * Specifies if the metallic texture contains the metallness information in its blue channel.
  37572. */
  37573. _this.useMetallnessFromMetallicTextureBlue = false;
  37574. /**
  37575. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  37576. */
  37577. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  37578. /**
  37579. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  37580. */
  37581. _this.useAmbientInGrayScale = false;
  37582. /**
  37583. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  37584. * The material will try to infer what glossiness each pixel should be.
  37585. */
  37586. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  37587. /**
  37588. * BJS is using an harcoded light falloff based on a manually sets up range.
  37589. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  37590. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  37591. */
  37592. _this.usePhysicalLightFalloff = true;
  37593. /**
  37594. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  37595. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  37596. */
  37597. _this.useRadianceOverAlpha = true;
  37598. /**
  37599. * Allows using the bump map in parallax mode.
  37600. */
  37601. _this.useParallax = false;
  37602. /**
  37603. * Allows using the bump map in parallax occlusion mode.
  37604. */
  37605. _this.useParallaxOcclusion = false;
  37606. /**
  37607. * Controls the scale bias of the parallax mode.
  37608. */
  37609. _this.parallaxScaleBias = 0.05;
  37610. /**
  37611. * If sets to true, disables all the lights affecting the material.
  37612. */
  37613. _this.disableLighting = false;
  37614. /**
  37615. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  37616. */
  37617. _this.forceIrradianceInFragment = false;
  37618. /**
  37619. * Number of Simultaneous lights allowed on the material.
  37620. */
  37621. _this.maxSimultaneousLights = 4;
  37622. /**
  37623. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  37624. */
  37625. _this.invertNormalMapX = false;
  37626. /**
  37627. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  37628. */
  37629. _this.invertNormalMapY = false;
  37630. /**
  37631. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  37632. */
  37633. _this.twoSidedLighting = false;
  37634. /**
  37635. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  37636. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  37637. */
  37638. _this.useAlphaFresnel = false;
  37639. /**
  37640. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  37641. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  37642. */
  37643. _this.useLinearAlphaFresnel = false;
  37644. /**
  37645. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  37646. * And/Or occlude the blended part.
  37647. */
  37648. _this.environmentBRDFTexture = null;
  37649. /**
  37650. * Force normal to face away from face.
  37651. */
  37652. _this.forceNormalForward = false;
  37653. /**
  37654. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  37655. * makes the reflect vector face the model (under horizon).
  37656. */
  37657. _this.useHorizonOcclusion = true;
  37658. /**
  37659. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  37660. * too much the area relying on ambient texture to define their ambient occlusion.
  37661. */
  37662. _this.useRadianceOcclusion = true;
  37663. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  37664. return _this;
  37665. }
  37666. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  37667. /**
  37668. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  37669. */
  37670. get: function () {
  37671. return this._PBRMATERIAL_OPAQUE;
  37672. },
  37673. enumerable: true,
  37674. configurable: true
  37675. });
  37676. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  37677. /**
  37678. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  37679. */
  37680. get: function () {
  37681. return this._PBRMATERIAL_ALPHATEST;
  37682. },
  37683. enumerable: true,
  37684. configurable: true
  37685. });
  37686. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  37687. /**
  37688. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  37689. */
  37690. get: function () {
  37691. return this._PBRMATERIAL_ALPHABLEND;
  37692. },
  37693. enumerable: true,
  37694. configurable: true
  37695. });
  37696. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  37697. /**
  37698. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  37699. * They are also discarded below the alpha cutoff threshold to improve performances.
  37700. */
  37701. get: function () {
  37702. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  37703. },
  37704. enumerable: true,
  37705. configurable: true
  37706. });
  37707. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  37708. /**
  37709. * Gets the image processing configuration used either in this material.
  37710. */
  37711. get: function () {
  37712. return this._imageProcessingConfiguration;
  37713. },
  37714. /**
  37715. * Sets the Default image processing configuration used either in the this material.
  37716. *
  37717. * If sets to null, the scene one is in use.
  37718. */
  37719. set: function (value) {
  37720. this._attachImageProcessingConfiguration(value);
  37721. // Ensure the effect will be rebuilt.
  37722. this._markAllSubMeshesAsTexturesDirty();
  37723. },
  37724. enumerable: true,
  37725. configurable: true
  37726. });
  37727. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  37728. /**
  37729. * Gets wether the color curves effect is enabled.
  37730. */
  37731. get: function () {
  37732. return this.imageProcessingConfiguration.colorCurvesEnabled;
  37733. },
  37734. /**
  37735. * Sets wether the color curves effect is enabled.
  37736. */
  37737. set: function (value) {
  37738. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  37739. },
  37740. enumerable: true,
  37741. configurable: true
  37742. });
  37743. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  37744. /**
  37745. * Gets wether the color grading effect is enabled.
  37746. */
  37747. get: function () {
  37748. return this.imageProcessingConfiguration.colorGradingEnabled;
  37749. },
  37750. /**
  37751. * Gets wether the color grading effect is enabled.
  37752. */
  37753. set: function (value) {
  37754. this.imageProcessingConfiguration.colorGradingEnabled = value;
  37755. },
  37756. enumerable: true,
  37757. configurable: true
  37758. });
  37759. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  37760. /**
  37761. * Gets wether tonemapping is enabled or not.
  37762. */
  37763. get: function () {
  37764. return this._imageProcessingConfiguration.toneMappingEnabled;
  37765. },
  37766. /**
  37767. * Sets wether tonemapping is enabled or not
  37768. */
  37769. set: function (value) {
  37770. this._imageProcessingConfiguration.toneMappingEnabled = value;
  37771. },
  37772. enumerable: true,
  37773. configurable: true
  37774. });
  37775. ;
  37776. ;
  37777. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  37778. /**
  37779. * The camera exposure used on this material.
  37780. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  37781. * This corresponds to a photographic exposure.
  37782. */
  37783. get: function () {
  37784. return this._imageProcessingConfiguration.exposure;
  37785. },
  37786. /**
  37787. * The camera exposure used on this material.
  37788. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  37789. * This corresponds to a photographic exposure.
  37790. */
  37791. set: function (value) {
  37792. this._imageProcessingConfiguration.exposure = value;
  37793. },
  37794. enumerable: true,
  37795. configurable: true
  37796. });
  37797. ;
  37798. ;
  37799. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  37800. /**
  37801. * Gets The camera contrast used on this material.
  37802. */
  37803. get: function () {
  37804. return this._imageProcessingConfiguration.contrast;
  37805. },
  37806. /**
  37807. * Sets The camera contrast used on this material.
  37808. */
  37809. set: function (value) {
  37810. this._imageProcessingConfiguration.contrast = value;
  37811. },
  37812. enumerable: true,
  37813. configurable: true
  37814. });
  37815. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  37816. /**
  37817. * Gets the Color Grading 2D Lookup Texture.
  37818. */
  37819. get: function () {
  37820. return this._imageProcessingConfiguration.colorGradingTexture;
  37821. },
  37822. /**
  37823. * Sets the Color Grading 2D Lookup Texture.
  37824. */
  37825. set: function (value) {
  37826. this._imageProcessingConfiguration.colorGradingTexture = value;
  37827. },
  37828. enumerable: true,
  37829. configurable: true
  37830. });
  37831. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  37832. /**
  37833. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  37834. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  37835. * 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;
  37836. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  37837. */
  37838. get: function () {
  37839. return this._imageProcessingConfiguration.colorCurves;
  37840. },
  37841. /**
  37842. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  37843. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  37844. * 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;
  37845. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  37846. */
  37847. set: function (value) {
  37848. this._imageProcessingConfiguration.colorCurves = value;
  37849. },
  37850. enumerable: true,
  37851. configurable: true
  37852. });
  37853. PBRMaterial.prototype.getClassName = function () {
  37854. return "PBRMaterial";
  37855. };
  37856. PBRMaterial.prototype.getActiveTextures = function () {
  37857. var activeTextures = _super.prototype.getActiveTextures.call(this);
  37858. if (this._albedoTexture) {
  37859. activeTextures.push(this._albedoTexture);
  37860. }
  37861. if (this._ambientTexture) {
  37862. activeTextures.push(this._ambientTexture);
  37863. }
  37864. if (this._opacityTexture) {
  37865. activeTextures.push(this._opacityTexture);
  37866. }
  37867. if (this._reflectionTexture) {
  37868. activeTextures.push(this._reflectionTexture);
  37869. }
  37870. if (this._emissiveTexture) {
  37871. activeTextures.push(this._emissiveTexture);
  37872. }
  37873. if (this._reflectivityTexture) {
  37874. activeTextures.push(this._reflectivityTexture);
  37875. }
  37876. if (this._metallicTexture) {
  37877. activeTextures.push(this._metallicTexture);
  37878. }
  37879. if (this._microSurfaceTexture) {
  37880. activeTextures.push(this._microSurfaceTexture);
  37881. }
  37882. if (this._bumpTexture) {
  37883. activeTextures.push(this._bumpTexture);
  37884. }
  37885. if (this._lightmapTexture) {
  37886. activeTextures.push(this._lightmapTexture);
  37887. }
  37888. if (this._refractionTexture) {
  37889. activeTextures.push(this._refractionTexture);
  37890. }
  37891. return activeTextures;
  37892. };
  37893. PBRMaterial.prototype.hasTexture = function (texture) {
  37894. if (_super.prototype.hasTexture.call(this, texture)) {
  37895. return true;
  37896. }
  37897. if (this._albedoTexture === texture) {
  37898. return true;
  37899. }
  37900. if (this._ambientTexture === texture) {
  37901. return true;
  37902. }
  37903. if (this._opacityTexture === texture) {
  37904. return true;
  37905. }
  37906. if (this._reflectionTexture === texture) {
  37907. return true;
  37908. }
  37909. if (this._reflectivityTexture === texture) {
  37910. return true;
  37911. }
  37912. if (this._metallicTexture === texture) {
  37913. return true;
  37914. }
  37915. if (this._microSurfaceTexture === texture) {
  37916. return true;
  37917. }
  37918. if (this._bumpTexture === texture) {
  37919. return true;
  37920. }
  37921. if (this._lightmapTexture === texture) {
  37922. return true;
  37923. }
  37924. if (this._refractionTexture === texture) {
  37925. return true;
  37926. }
  37927. return false;
  37928. };
  37929. PBRMaterial.prototype.clone = function (name) {
  37930. var _this = this;
  37931. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  37932. clone.id = name;
  37933. clone.name = name;
  37934. return clone;
  37935. };
  37936. PBRMaterial.prototype.serialize = function () {
  37937. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  37938. serializationObject.customType = "BABYLON.PBRMaterial";
  37939. return serializationObject;
  37940. };
  37941. // Statics
  37942. PBRMaterial.Parse = function (source, scene, rootUrl) {
  37943. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  37944. };
  37945. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  37946. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  37947. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  37948. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  37949. __decorate([
  37950. BABYLON.serialize(),
  37951. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37952. ], PBRMaterial.prototype, "directIntensity", void 0);
  37953. __decorate([
  37954. BABYLON.serialize(),
  37955. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37956. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  37957. __decorate([
  37958. BABYLON.serialize(),
  37959. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37960. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  37961. __decorate([
  37962. BABYLON.serialize(),
  37963. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37964. ], PBRMaterial.prototype, "specularIntensity", void 0);
  37965. __decorate([
  37966. BABYLON.serialize(),
  37967. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37968. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  37969. __decorate([
  37970. BABYLON.serializeAsTexture(),
  37971. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37972. ], PBRMaterial.prototype, "albedoTexture", void 0);
  37973. __decorate([
  37974. BABYLON.serializeAsTexture(),
  37975. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37976. ], PBRMaterial.prototype, "ambientTexture", void 0);
  37977. __decorate([
  37978. BABYLON.serialize(),
  37979. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37980. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  37981. __decorate([
  37982. BABYLON.serializeAsTexture(),
  37983. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37984. ], PBRMaterial.prototype, "opacityTexture", void 0);
  37985. __decorate([
  37986. BABYLON.serializeAsTexture(),
  37987. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37988. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  37989. __decorate([
  37990. BABYLON.serializeAsTexture(),
  37991. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37992. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  37993. __decorate([
  37994. BABYLON.serializeAsTexture(),
  37995. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  37996. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  37997. __decorate([
  37998. BABYLON.serializeAsTexture(),
  37999. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38000. ], PBRMaterial.prototype, "metallicTexture", void 0);
  38001. __decorate([
  38002. BABYLON.serialize(),
  38003. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38004. ], PBRMaterial.prototype, "metallic", void 0);
  38005. __decorate([
  38006. BABYLON.serialize(),
  38007. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38008. ], PBRMaterial.prototype, "roughness", void 0);
  38009. __decorate([
  38010. BABYLON.serializeAsTexture(),
  38011. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38012. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  38013. __decorate([
  38014. BABYLON.serializeAsTexture(),
  38015. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38016. ], PBRMaterial.prototype, "bumpTexture", void 0);
  38017. __decorate([
  38018. BABYLON.serializeAsTexture(),
  38019. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  38020. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  38021. __decorate([
  38022. BABYLON.serializeAsTexture(),
  38023. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38024. ], PBRMaterial.prototype, "refractionTexture", void 0);
  38025. __decorate([
  38026. BABYLON.serializeAsColor3("ambient"),
  38027. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38028. ], PBRMaterial.prototype, "ambientColor", void 0);
  38029. __decorate([
  38030. BABYLON.serializeAsColor3("albedo"),
  38031. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38032. ], PBRMaterial.prototype, "albedoColor", void 0);
  38033. __decorate([
  38034. BABYLON.serializeAsColor3("reflectivity"),
  38035. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38036. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  38037. __decorate([
  38038. BABYLON.serializeAsColor3("reflection"),
  38039. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38040. ], PBRMaterial.prototype, "reflectionColor", void 0);
  38041. __decorate([
  38042. BABYLON.serializeAsColor3("emissive"),
  38043. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38044. ], PBRMaterial.prototype, "emissiveColor", void 0);
  38045. __decorate([
  38046. BABYLON.serialize(),
  38047. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38048. ], PBRMaterial.prototype, "microSurface", void 0);
  38049. __decorate([
  38050. BABYLON.serialize(),
  38051. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38052. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  38053. __decorate([
  38054. BABYLON.serialize(),
  38055. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38056. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  38057. __decorate([
  38058. BABYLON.serialize(),
  38059. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38060. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  38061. __decorate([
  38062. BABYLON.serialize(),
  38063. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38064. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  38065. __decorate([
  38066. BABYLON.serialize(),
  38067. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38068. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  38069. __decorate([
  38070. BABYLON.serialize(),
  38071. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38072. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  38073. __decorate([
  38074. BABYLON.serialize(),
  38075. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38076. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  38077. __decorate([
  38078. BABYLON.serialize(),
  38079. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38080. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  38081. __decorate([
  38082. BABYLON.serialize(),
  38083. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38084. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  38085. __decorate([
  38086. BABYLON.serialize(),
  38087. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38088. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  38089. __decorate([
  38090. BABYLON.serialize(),
  38091. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38092. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  38093. __decorate([
  38094. BABYLON.serialize(),
  38095. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38096. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  38097. __decorate([
  38098. BABYLON.serialize(),
  38099. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38100. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  38101. __decorate([
  38102. BABYLON.serialize(),
  38103. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38104. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  38105. __decorate([
  38106. BABYLON.serialize(),
  38107. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38108. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  38109. __decorate([
  38110. BABYLON.serialize(),
  38111. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38112. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  38113. __decorate([
  38114. BABYLON.serialize(),
  38115. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38116. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  38117. __decorate([
  38118. BABYLON.serialize(),
  38119. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38120. ], PBRMaterial.prototype, "useParallax", void 0);
  38121. __decorate([
  38122. BABYLON.serialize(),
  38123. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38124. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  38125. __decorate([
  38126. BABYLON.serialize(),
  38127. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38128. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  38129. __decorate([
  38130. BABYLON.serialize(),
  38131. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  38132. ], PBRMaterial.prototype, "disableLighting", void 0);
  38133. __decorate([
  38134. BABYLON.serialize(),
  38135. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38136. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  38137. __decorate([
  38138. BABYLON.serialize(),
  38139. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  38140. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  38141. __decorate([
  38142. BABYLON.serialize(),
  38143. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38144. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  38145. __decorate([
  38146. BABYLON.serialize(),
  38147. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38148. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  38149. __decorate([
  38150. BABYLON.serialize(),
  38151. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38152. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  38153. __decorate([
  38154. BABYLON.serialize(),
  38155. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38156. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  38157. __decorate([
  38158. BABYLON.serialize(),
  38159. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38160. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  38161. __decorate([
  38162. BABYLON.serializeAsTexture(),
  38163. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38164. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  38165. __decorate([
  38166. BABYLON.serialize(),
  38167. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38168. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  38169. __decorate([
  38170. BABYLON.serialize(),
  38171. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38172. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  38173. __decorate([
  38174. BABYLON.serialize(),
  38175. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38176. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  38177. return PBRMaterial;
  38178. }(BABYLON.PBRBaseMaterial));
  38179. BABYLON.PBRMaterial = PBRMaterial;
  38180. })(BABYLON || (BABYLON = {}));
  38181. //# sourceMappingURL=babylon.pbrMaterial.js.map
  38182. var BABYLON;
  38183. (function (BABYLON) {
  38184. /**
  38185. * The PBR material of BJS following the metal roughness convention.
  38186. *
  38187. * This fits to the PBR convention in the GLTF definition:
  38188. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  38189. */
  38190. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  38191. __extends(PBRMetallicRoughnessMaterial, _super);
  38192. /**
  38193. * Instantiates a new PBRMetalRoughnessMaterial instance.
  38194. *
  38195. * @param name The material name
  38196. * @param scene The scene the material will be use in.
  38197. */
  38198. function PBRMetallicRoughnessMaterial(name, scene) {
  38199. var _this = _super.call(this, name, scene) || this;
  38200. _this._useRoughnessFromMetallicTextureAlpha = false;
  38201. _this._useRoughnessFromMetallicTextureGreen = true;
  38202. _this._useMetallnessFromMetallicTextureBlue = true;
  38203. return _this;
  38204. }
  38205. /**
  38206. * Return the currrent class name of the material.
  38207. */
  38208. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  38209. return "PBRMetallicRoughnessMaterial";
  38210. };
  38211. /**
  38212. * Return the active textures of the material.
  38213. */
  38214. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  38215. var activeTextures = _super.prototype.getActiveTextures.call(this);
  38216. if (this.baseTexture) {
  38217. activeTextures.push(this.baseTexture);
  38218. }
  38219. if (this.metallicRoughnessTexture) {
  38220. activeTextures.push(this.metallicRoughnessTexture);
  38221. }
  38222. return activeTextures;
  38223. };
  38224. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  38225. if (_super.prototype.hasTexture.call(this, texture)) {
  38226. return true;
  38227. }
  38228. if (this.baseTexture === texture) {
  38229. return true;
  38230. }
  38231. if (this.metallicRoughnessTexture === texture) {
  38232. return true;
  38233. }
  38234. return false;
  38235. };
  38236. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  38237. var _this = this;
  38238. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  38239. clone.id = name;
  38240. clone.name = name;
  38241. return clone;
  38242. };
  38243. /**
  38244. * Serialize the material to a parsable JSON object.
  38245. */
  38246. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  38247. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  38248. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  38249. return serializationObject;
  38250. };
  38251. /**
  38252. * Parses a JSON object correponding to the serialize function.
  38253. */
  38254. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  38255. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  38256. };
  38257. __decorate([
  38258. BABYLON.serializeAsColor3(),
  38259. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  38260. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  38261. __decorate([
  38262. BABYLON.serializeAsTexture(),
  38263. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  38264. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  38265. __decorate([
  38266. BABYLON.serialize(),
  38267. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38268. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  38269. __decorate([
  38270. BABYLON.serialize(),
  38271. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  38272. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  38273. __decorate([
  38274. BABYLON.serializeAsTexture(),
  38275. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  38276. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  38277. return PBRMetallicRoughnessMaterial;
  38278. }(BABYLON.Internals.PBRBaseSimpleMaterial));
  38279. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  38280. })(BABYLON || (BABYLON = {}));
  38281. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  38282. var BABYLON;
  38283. (function (BABYLON) {
  38284. /**
  38285. * The PBR material of BJS following the specular glossiness convention.
  38286. *
  38287. * This fits to the PBR convention in the GLTF definition:
  38288. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  38289. */
  38290. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  38291. __extends(PBRSpecularGlossinessMaterial, _super);
  38292. /**
  38293. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  38294. *
  38295. * @param name The material name
  38296. * @param scene The scene the material will be use in.
  38297. */
  38298. function PBRSpecularGlossinessMaterial(name, scene) {
  38299. var _this = _super.call(this, name, scene) || this;
  38300. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  38301. return _this;
  38302. }
  38303. /**
  38304. * Return the currrent class name of the material.
  38305. */
  38306. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  38307. return "PBRSpecularGlossinessMaterial";
  38308. };
  38309. /**
  38310. * Return the active textures of the material.
  38311. */
  38312. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  38313. var activeTextures = _super.prototype.getActiveTextures.call(this);
  38314. if (this.diffuseTexture) {
  38315. activeTextures.push(this.diffuseTexture);
  38316. }
  38317. if (this.specularGlossinessTexture) {
  38318. activeTextures.push(this.specularGlossinessTexture);
  38319. }
  38320. return activeTextures;
  38321. };
  38322. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  38323. if (_super.prototype.hasTexture.call(this, texture)) {
  38324. return true;
  38325. }
  38326. if (this.diffuseTexture === texture) {
  38327. return true;
  38328. }
  38329. if (this.specularGlossinessTexture === texture) {
  38330. return true;
  38331. }
  38332. return false;
  38333. };
  38334. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  38335. var _this = this;
  38336. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  38337. clone.id = name;
  38338. clone.name = name;
  38339. return clone;
  38340. };
  38341. /**
  38342. * Serialize the material to a parsable JSON object.
  38343. */
  38344. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  38345. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  38346. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  38347. return serializationObject;
  38348. };
  38349. /**
  38350. * Parses a JSON object correponding to the serialize function.
  38351. */
  38352. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  38353. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  38354. };
  38355. __decorate([
  38356. BABYLON.serializeAsColor3("diffuse"),
  38357. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  38358. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  38359. __decorate([
  38360. BABYLON.serializeAsTexture(),
  38361. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  38362. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  38363. __decorate([
  38364. BABYLON.serializeAsColor3("specular"),
  38365. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  38366. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  38367. __decorate([
  38368. BABYLON.serialize(),
  38369. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  38370. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  38371. __decorate([
  38372. BABYLON.serializeAsTexture(),
  38373. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  38374. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  38375. return PBRSpecularGlossinessMaterial;
  38376. }(BABYLON.Internals.PBRBaseSimpleMaterial));
  38377. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  38378. })(BABYLON || (BABYLON = {}));
  38379. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  38380. var BABYLON;
  38381. (function (BABYLON) {
  38382. BABYLON.CameraInputTypes = {};
  38383. var CameraInputsManager = /** @class */ (function () {
  38384. function CameraInputsManager(camera) {
  38385. this.attached = {};
  38386. this.camera = camera;
  38387. this.checkInputs = function () { };
  38388. }
  38389. CameraInputsManager.prototype.add = function (input) {
  38390. var type = input.getSimpleName();
  38391. if (this.attached[type]) {
  38392. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  38393. return;
  38394. }
  38395. this.attached[type] = input;
  38396. input.camera = this.camera;
  38397. //for checkInputs, we are dynamically creating a function
  38398. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  38399. if (input.checkInputs) {
  38400. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  38401. }
  38402. if (this.attachedElement) {
  38403. input.attachControl(this.attachedElement);
  38404. }
  38405. };
  38406. CameraInputsManager.prototype.remove = function (inputToRemove) {
  38407. for (var cam in this.attached) {
  38408. var input = this.attached[cam];
  38409. if (input === inputToRemove) {
  38410. input.detachControl(this.attachedElement);
  38411. input.camera = null;
  38412. delete this.attached[cam];
  38413. this.rebuildInputCheck();
  38414. }
  38415. }
  38416. };
  38417. CameraInputsManager.prototype.removeByType = function (inputType) {
  38418. for (var cam in this.attached) {
  38419. var input = this.attached[cam];
  38420. if (input.getClassName() === inputType) {
  38421. input.detachControl(this.attachedElement);
  38422. input.camera = null;
  38423. delete this.attached[cam];
  38424. this.rebuildInputCheck();
  38425. }
  38426. }
  38427. };
  38428. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  38429. var current = this.checkInputs;
  38430. return function () {
  38431. current();
  38432. fn();
  38433. };
  38434. };
  38435. CameraInputsManager.prototype.attachInput = function (input) {
  38436. if (this.attachedElement) {
  38437. input.attachControl(this.attachedElement, this.noPreventDefault);
  38438. }
  38439. };
  38440. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  38441. if (noPreventDefault === void 0) { noPreventDefault = false; }
  38442. if (this.attachedElement) {
  38443. return;
  38444. }
  38445. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  38446. this.attachedElement = element;
  38447. this.noPreventDefault = noPreventDefault;
  38448. for (var cam in this.attached) {
  38449. this.attached[cam].attachControl(element, noPreventDefault);
  38450. }
  38451. };
  38452. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  38453. if (disconnect === void 0) { disconnect = false; }
  38454. if (this.attachedElement !== element) {
  38455. return;
  38456. }
  38457. for (var cam in this.attached) {
  38458. this.attached[cam].detachControl(element);
  38459. if (disconnect) {
  38460. this.attached[cam].camera = null;
  38461. }
  38462. }
  38463. this.attachedElement = null;
  38464. };
  38465. CameraInputsManager.prototype.rebuildInputCheck = function () {
  38466. this.checkInputs = function () { };
  38467. for (var cam in this.attached) {
  38468. var input = this.attached[cam];
  38469. if (input.checkInputs) {
  38470. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  38471. }
  38472. }
  38473. };
  38474. CameraInputsManager.prototype.clear = function () {
  38475. if (this.attachedElement) {
  38476. this.detachElement(this.attachedElement, true);
  38477. }
  38478. this.attached = {};
  38479. this.attachedElement = null;
  38480. this.checkInputs = function () { };
  38481. };
  38482. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  38483. var inputs = {};
  38484. for (var cam in this.attached) {
  38485. var input = this.attached[cam];
  38486. var res = BABYLON.SerializationHelper.Serialize(input);
  38487. inputs[input.getClassName()] = res;
  38488. }
  38489. serializedCamera.inputsmgr = inputs;
  38490. };
  38491. CameraInputsManager.prototype.parse = function (parsedCamera) {
  38492. var parsedInputs = parsedCamera.inputsmgr;
  38493. if (parsedInputs) {
  38494. this.clear();
  38495. for (var n in parsedInputs) {
  38496. var construct = BABYLON.CameraInputTypes[n];
  38497. if (construct) {
  38498. var parsedinput = parsedInputs[n];
  38499. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  38500. this.add(input);
  38501. }
  38502. }
  38503. }
  38504. else {
  38505. //2016-03-08 this part is for managing backward compatibility
  38506. for (var n in this.attached) {
  38507. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  38508. if (construct) {
  38509. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  38510. this.remove(this.attached[n]);
  38511. this.add(input);
  38512. }
  38513. }
  38514. }
  38515. };
  38516. return CameraInputsManager;
  38517. }());
  38518. BABYLON.CameraInputsManager = CameraInputsManager;
  38519. })(BABYLON || (BABYLON = {}));
  38520. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  38521. var BABYLON;
  38522. (function (BABYLON) {
  38523. var FreeCameraMouseInput = /** @class */ (function () {
  38524. function FreeCameraMouseInput(touchEnabled) {
  38525. if (touchEnabled === void 0) { touchEnabled = true; }
  38526. this.touchEnabled = touchEnabled;
  38527. this.buttons = [0, 1, 2];
  38528. this.angularSensibility = 2000.0;
  38529. this.previousPosition = null;
  38530. }
  38531. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  38532. var _this = this;
  38533. var engine = this.camera.getEngine();
  38534. if (!this._pointerInput) {
  38535. this._pointerInput = function (p, s) {
  38536. var evt = p.event;
  38537. if (engine.isInVRExclusivePointerMode) {
  38538. return;
  38539. }
  38540. if (!_this.touchEnabled && evt.pointerType === "touch") {
  38541. return;
  38542. }
  38543. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  38544. return;
  38545. }
  38546. var srcElement = (evt.srcElement || evt.target);
  38547. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  38548. try {
  38549. srcElement.setPointerCapture(evt.pointerId);
  38550. }
  38551. catch (e) {
  38552. //Nothing to do with the error. Execution will continue.
  38553. }
  38554. _this.previousPosition = {
  38555. x: evt.clientX,
  38556. y: evt.clientY
  38557. };
  38558. if (!noPreventDefault) {
  38559. evt.preventDefault();
  38560. element.focus();
  38561. }
  38562. }
  38563. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  38564. try {
  38565. srcElement.releasePointerCapture(evt.pointerId);
  38566. }
  38567. catch (e) {
  38568. //Nothing to do with the error.
  38569. }
  38570. _this.previousPosition = null;
  38571. if (!noPreventDefault) {
  38572. evt.preventDefault();
  38573. }
  38574. }
  38575. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  38576. if (!_this.previousPosition || engine.isPointerLock) {
  38577. return;
  38578. }
  38579. var offsetX = evt.clientX - _this.previousPosition.x;
  38580. var offsetY = evt.clientY - _this.previousPosition.y;
  38581. if (_this.camera.getScene().useRightHandedSystem) {
  38582. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  38583. }
  38584. else {
  38585. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  38586. }
  38587. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  38588. _this.previousPosition = {
  38589. x: evt.clientX,
  38590. y: evt.clientY
  38591. };
  38592. if (!noPreventDefault) {
  38593. evt.preventDefault();
  38594. }
  38595. }
  38596. };
  38597. }
  38598. this._onMouseMove = function (evt) {
  38599. if (!engine.isPointerLock) {
  38600. return;
  38601. }
  38602. if (engine.isInVRExclusivePointerMode) {
  38603. return;
  38604. }
  38605. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  38606. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  38607. if (_this.camera.getScene().useRightHandedSystem) {
  38608. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  38609. }
  38610. else {
  38611. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  38612. }
  38613. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  38614. _this.previousPosition = null;
  38615. if (!noPreventDefault) {
  38616. evt.preventDefault();
  38617. }
  38618. };
  38619. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  38620. element.addEventListener("mousemove", this._onMouseMove, false);
  38621. };
  38622. FreeCameraMouseInput.prototype.detachControl = function (element) {
  38623. if (this._observer && element) {
  38624. this.camera.getScene().onPointerObservable.remove(this._observer);
  38625. if (this._onMouseMove) {
  38626. element.removeEventListener("mousemove", this._onMouseMove);
  38627. }
  38628. this._observer = null;
  38629. this._onMouseMove = null;
  38630. this.previousPosition = null;
  38631. }
  38632. };
  38633. FreeCameraMouseInput.prototype.getClassName = function () {
  38634. return "FreeCameraMouseInput";
  38635. };
  38636. FreeCameraMouseInput.prototype.getSimpleName = function () {
  38637. return "mouse";
  38638. };
  38639. __decorate([
  38640. BABYLON.serialize()
  38641. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  38642. __decorate([
  38643. BABYLON.serialize()
  38644. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  38645. return FreeCameraMouseInput;
  38646. }());
  38647. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  38648. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  38649. })(BABYLON || (BABYLON = {}));
  38650. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  38651. var BABYLON;
  38652. (function (BABYLON) {
  38653. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  38654. function FreeCameraKeyboardMoveInput() {
  38655. this._keys = new Array();
  38656. this.keysUp = [38];
  38657. this.keysDown = [40];
  38658. this.keysLeft = [37];
  38659. this.keysRight = [39];
  38660. }
  38661. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  38662. var _this = this;
  38663. if (this._onCanvasBlurObserver) {
  38664. return;
  38665. }
  38666. this._scene = this.camera.getScene();
  38667. this._engine = this._scene.getEngine();
  38668. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  38669. _this._keys = [];
  38670. });
  38671. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  38672. var evt = info.event;
  38673. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  38674. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  38675. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  38676. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  38677. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  38678. var index = _this._keys.indexOf(evt.keyCode);
  38679. if (index === -1) {
  38680. _this._keys.push(evt.keyCode);
  38681. }
  38682. if (!noPreventDefault) {
  38683. evt.preventDefault();
  38684. }
  38685. }
  38686. }
  38687. else {
  38688. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  38689. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  38690. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  38691. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  38692. var index = _this._keys.indexOf(evt.keyCode);
  38693. if (index >= 0) {
  38694. _this._keys.splice(index, 1);
  38695. }
  38696. if (!noPreventDefault) {
  38697. evt.preventDefault();
  38698. }
  38699. }
  38700. }
  38701. });
  38702. };
  38703. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  38704. if (this._scene) {
  38705. if (this._onKeyboardObserver) {
  38706. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  38707. }
  38708. if (this._onCanvasBlurObserver) {
  38709. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  38710. }
  38711. this._onKeyboardObserver = null;
  38712. this._onCanvasBlurObserver = null;
  38713. }
  38714. this._keys = [];
  38715. };
  38716. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  38717. if (this._onKeyboardObserver) {
  38718. var camera = this.camera;
  38719. // Keyboard
  38720. for (var index = 0; index < this._keys.length; index++) {
  38721. var keyCode = this._keys[index];
  38722. var speed = camera._computeLocalCameraSpeed();
  38723. if (this.keysLeft.indexOf(keyCode) !== -1) {
  38724. camera._localDirection.copyFromFloats(-speed, 0, 0);
  38725. }
  38726. else if (this.keysUp.indexOf(keyCode) !== -1) {
  38727. camera._localDirection.copyFromFloats(0, 0, speed);
  38728. }
  38729. else if (this.keysRight.indexOf(keyCode) !== -1) {
  38730. camera._localDirection.copyFromFloats(speed, 0, 0);
  38731. }
  38732. else if (this.keysDown.indexOf(keyCode) !== -1) {
  38733. camera._localDirection.copyFromFloats(0, 0, -speed);
  38734. }
  38735. if (camera.getScene().useRightHandedSystem) {
  38736. camera._localDirection.z *= -1;
  38737. }
  38738. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  38739. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  38740. camera.cameraDirection.addInPlace(camera._transformedDirection);
  38741. }
  38742. }
  38743. };
  38744. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  38745. return "FreeCameraKeyboardMoveInput";
  38746. };
  38747. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  38748. this._keys = [];
  38749. };
  38750. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  38751. return "keyboard";
  38752. };
  38753. __decorate([
  38754. BABYLON.serialize()
  38755. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  38756. __decorate([
  38757. BABYLON.serialize()
  38758. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  38759. __decorate([
  38760. BABYLON.serialize()
  38761. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  38762. __decorate([
  38763. BABYLON.serialize()
  38764. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  38765. return FreeCameraKeyboardMoveInput;
  38766. }());
  38767. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  38768. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  38769. })(BABYLON || (BABYLON = {}));
  38770. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  38771. var BABYLON;
  38772. (function (BABYLON) {
  38773. var FreeCameraInputsManager = /** @class */ (function (_super) {
  38774. __extends(FreeCameraInputsManager, _super);
  38775. function FreeCameraInputsManager(camera) {
  38776. return _super.call(this, camera) || this;
  38777. }
  38778. FreeCameraInputsManager.prototype.addKeyboard = function () {
  38779. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  38780. return this;
  38781. };
  38782. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  38783. if (touchEnabled === void 0) { touchEnabled = true; }
  38784. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  38785. return this;
  38786. };
  38787. FreeCameraInputsManager.prototype.addGamepad = function () {
  38788. this.add(new BABYLON.FreeCameraGamepadInput());
  38789. return this;
  38790. };
  38791. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  38792. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  38793. return this;
  38794. };
  38795. FreeCameraInputsManager.prototype.addTouch = function () {
  38796. this.add(new BABYLON.FreeCameraTouchInput());
  38797. return this;
  38798. };
  38799. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  38800. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  38801. return this;
  38802. };
  38803. return FreeCameraInputsManager;
  38804. }(BABYLON.CameraInputsManager));
  38805. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  38806. })(BABYLON || (BABYLON = {}));
  38807. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  38808. var BABYLON;
  38809. (function (BABYLON) {
  38810. var TargetCamera = /** @class */ (function (_super) {
  38811. __extends(TargetCamera, _super);
  38812. function TargetCamera(name, position, scene) {
  38813. var _this = _super.call(this, name, position, scene) || this;
  38814. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  38815. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  38816. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  38817. _this.speed = 2.0;
  38818. _this.noRotationConstraint = false;
  38819. _this.lockedTarget = null;
  38820. _this._currentTarget = BABYLON.Vector3.Zero();
  38821. _this._viewMatrix = BABYLON.Matrix.Zero();
  38822. _this._camMatrix = BABYLON.Matrix.Zero();
  38823. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  38824. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  38825. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  38826. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  38827. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  38828. _this._lookAtTemp = BABYLON.Matrix.Zero();
  38829. _this._tempMatrix = BABYLON.Matrix.Zero();
  38830. return _this;
  38831. }
  38832. TargetCamera.prototype.getFrontPosition = function (distance) {
  38833. var direction = this.getTarget().subtract(this.position);
  38834. direction.normalize();
  38835. direction.scaleInPlace(distance);
  38836. return this.globalPosition.add(direction);
  38837. };
  38838. TargetCamera.prototype._getLockedTargetPosition = function () {
  38839. if (!this.lockedTarget) {
  38840. return null;
  38841. }
  38842. if (this.lockedTarget.absolutePosition) {
  38843. this.lockedTarget.computeWorldMatrix();
  38844. }
  38845. return this.lockedTarget.absolutePosition || this.lockedTarget;
  38846. };
  38847. TargetCamera.prototype.storeState = function () {
  38848. this._storedPosition = this.position.clone();
  38849. this._storedRotation = this.rotation.clone();
  38850. if (this.rotationQuaternion) {
  38851. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  38852. }
  38853. return _super.prototype.storeState.call(this);
  38854. };
  38855. /**
  38856. * Restored camera state. You must call storeState() first
  38857. */
  38858. TargetCamera.prototype._restoreStateValues = function () {
  38859. if (!_super.prototype._restoreStateValues.call(this)) {
  38860. return false;
  38861. }
  38862. this.position = this._storedPosition.clone();
  38863. this.rotation = this._storedRotation.clone();
  38864. if (this.rotationQuaternion) {
  38865. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  38866. }
  38867. this.cameraDirection.copyFromFloats(0, 0, 0);
  38868. this.cameraRotation.copyFromFloats(0, 0);
  38869. return true;
  38870. };
  38871. // Cache
  38872. TargetCamera.prototype._initCache = function () {
  38873. _super.prototype._initCache.call(this);
  38874. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  38875. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  38876. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  38877. };
  38878. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  38879. if (!ignoreParentClass) {
  38880. _super.prototype._updateCache.call(this);
  38881. }
  38882. var lockedTargetPosition = this._getLockedTargetPosition();
  38883. if (!lockedTargetPosition) {
  38884. this._cache.lockedTarget = null;
  38885. }
  38886. else {
  38887. if (!this._cache.lockedTarget) {
  38888. this._cache.lockedTarget = lockedTargetPosition.clone();
  38889. }
  38890. else {
  38891. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  38892. }
  38893. }
  38894. this._cache.rotation.copyFrom(this.rotation);
  38895. if (this.rotationQuaternion)
  38896. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  38897. };
  38898. // Synchronized
  38899. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  38900. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  38901. return false;
  38902. }
  38903. var lockedTargetPosition = this._getLockedTargetPosition();
  38904. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  38905. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  38906. };
  38907. // Methods
  38908. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  38909. var engine = this.getEngine();
  38910. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  38911. };
  38912. // Target
  38913. TargetCamera.prototype.setTarget = function (target) {
  38914. this.upVector.normalize();
  38915. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  38916. this._camMatrix.invert();
  38917. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  38918. var vDir = target.subtract(this.position);
  38919. if (vDir.x >= 0.0) {
  38920. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  38921. }
  38922. else {
  38923. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  38924. }
  38925. this.rotation.z = 0;
  38926. if (isNaN(this.rotation.x)) {
  38927. this.rotation.x = 0;
  38928. }
  38929. if (isNaN(this.rotation.y)) {
  38930. this.rotation.y = 0;
  38931. }
  38932. if (isNaN(this.rotation.z)) {
  38933. this.rotation.z = 0;
  38934. }
  38935. if (this.rotationQuaternion) {
  38936. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  38937. }
  38938. };
  38939. /**
  38940. * Return the current target position of the camera. This value is expressed in local space.
  38941. */
  38942. TargetCamera.prototype.getTarget = function () {
  38943. return this._currentTarget;
  38944. };
  38945. TargetCamera.prototype._decideIfNeedsToMove = function () {
  38946. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  38947. };
  38948. TargetCamera.prototype._updatePosition = function () {
  38949. if (this.parent) {
  38950. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  38951. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  38952. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  38953. return;
  38954. }
  38955. this.position.addInPlace(this.cameraDirection);
  38956. };
  38957. TargetCamera.prototype._checkInputs = function () {
  38958. var needToMove = this._decideIfNeedsToMove();
  38959. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  38960. // Move
  38961. if (needToMove) {
  38962. this._updatePosition();
  38963. }
  38964. // Rotate
  38965. if (needToRotate) {
  38966. this.rotation.x += this.cameraRotation.x;
  38967. this.rotation.y += this.cameraRotation.y;
  38968. //rotate, if quaternion is set and rotation was used
  38969. if (this.rotationQuaternion) {
  38970. var len = this.rotation.lengthSquared();
  38971. if (len) {
  38972. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  38973. }
  38974. }
  38975. if (!this.noRotationConstraint) {
  38976. var limit = (Math.PI / 2) * 0.95;
  38977. if (this.rotation.x > limit)
  38978. this.rotation.x = limit;
  38979. if (this.rotation.x < -limit)
  38980. this.rotation.x = -limit;
  38981. }
  38982. }
  38983. // Inertia
  38984. if (needToMove) {
  38985. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  38986. this.cameraDirection.x = 0;
  38987. }
  38988. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  38989. this.cameraDirection.y = 0;
  38990. }
  38991. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  38992. this.cameraDirection.z = 0;
  38993. }
  38994. this.cameraDirection.scaleInPlace(this.inertia);
  38995. }
  38996. if (needToRotate) {
  38997. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  38998. this.cameraRotation.x = 0;
  38999. }
  39000. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  39001. this.cameraRotation.y = 0;
  39002. }
  39003. this.cameraRotation.scaleInPlace(this.inertia);
  39004. }
  39005. _super.prototype._checkInputs.call(this);
  39006. };
  39007. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  39008. if (this.rotationQuaternion) {
  39009. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  39010. }
  39011. else {
  39012. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  39013. }
  39014. //update the up vector!
  39015. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  39016. };
  39017. TargetCamera.prototype._getViewMatrix = function () {
  39018. if (this.lockedTarget) {
  39019. this.setTarget(this._getLockedTargetPosition());
  39020. }
  39021. // Compute
  39022. this._updateCameraRotationMatrix();
  39023. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  39024. // Computing target and final matrix
  39025. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  39026. if (this.getScene().useRightHandedSystem) {
  39027. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  39028. }
  39029. else {
  39030. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  39031. }
  39032. return this._viewMatrix;
  39033. };
  39034. /**
  39035. * @override
  39036. * Override Camera.createRigCamera
  39037. */
  39038. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  39039. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  39040. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  39041. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  39042. if (!this.rotationQuaternion) {
  39043. this.rotationQuaternion = new BABYLON.Quaternion();
  39044. }
  39045. rigCamera._cameraRigParams = {};
  39046. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  39047. }
  39048. return rigCamera;
  39049. }
  39050. return null;
  39051. };
  39052. /**
  39053. * @override
  39054. * Override Camera._updateRigCameras
  39055. */
  39056. TargetCamera.prototype._updateRigCameras = function () {
  39057. var camLeft = this._rigCameras[0];
  39058. var camRight = this._rigCameras[1];
  39059. switch (this.cameraRigMode) {
  39060. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  39061. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  39062. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  39063. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  39064. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  39065. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  39066. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  39067. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  39068. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  39069. camLeft.setTarget(this.getTarget());
  39070. camRight.setTarget(this.getTarget());
  39071. break;
  39072. case BABYLON.Camera.RIG_MODE_VR:
  39073. if (camLeft.rotationQuaternion) {
  39074. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  39075. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  39076. }
  39077. else {
  39078. camLeft.rotation.copyFrom(this.rotation);
  39079. camRight.rotation.copyFrom(this.rotation);
  39080. }
  39081. camLeft.position.copyFrom(this.position);
  39082. camRight.position.copyFrom(this.position);
  39083. break;
  39084. }
  39085. _super.prototype._updateRigCameras.call(this);
  39086. };
  39087. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  39088. if (!this._rigCamTransformMatrix) {
  39089. this._rigCamTransformMatrix = new BABYLON.Matrix();
  39090. }
  39091. var target = this.getTarget();
  39092. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  39093. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  39094. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  39095. };
  39096. TargetCamera.prototype.getClassName = function () {
  39097. return "TargetCamera";
  39098. };
  39099. __decorate([
  39100. BABYLON.serializeAsVector3()
  39101. ], TargetCamera.prototype, "rotation", void 0);
  39102. __decorate([
  39103. BABYLON.serialize()
  39104. ], TargetCamera.prototype, "speed", void 0);
  39105. __decorate([
  39106. BABYLON.serializeAsMeshReference("lockedTargetId")
  39107. ], TargetCamera.prototype, "lockedTarget", void 0);
  39108. return TargetCamera;
  39109. }(BABYLON.Camera));
  39110. BABYLON.TargetCamera = TargetCamera;
  39111. })(BABYLON || (BABYLON = {}));
  39112. //# sourceMappingURL=babylon.targetCamera.js.map
  39113. var BABYLON;
  39114. (function (BABYLON) {
  39115. var FreeCamera = /** @class */ (function (_super) {
  39116. __extends(FreeCamera, _super);
  39117. function FreeCamera(name, position, scene) {
  39118. var _this = _super.call(this, name, position, scene) || this;
  39119. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  39120. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  39121. _this.checkCollisions = false;
  39122. _this.applyGravity = false;
  39123. _this._needMoveForGravity = false;
  39124. _this._oldPosition = BABYLON.Vector3.Zero();
  39125. _this._diffPosition = BABYLON.Vector3.Zero();
  39126. _this._newPosition = BABYLON.Vector3.Zero();
  39127. // Collisions
  39128. _this._collisionMask = -1;
  39129. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  39130. if (collidedMesh === void 0) { collidedMesh = null; }
  39131. //TODO move this to the collision coordinator!
  39132. if (_this.getScene().workerCollisions)
  39133. newPosition.multiplyInPlace(_this._collider._radius);
  39134. var updatePosition = function (newPos) {
  39135. _this._newPosition.copyFrom(newPos);
  39136. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  39137. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  39138. _this.position.addInPlace(_this._diffPosition);
  39139. if (_this.onCollide && collidedMesh) {
  39140. _this.onCollide(collidedMesh);
  39141. }
  39142. }
  39143. };
  39144. updatePosition(newPosition);
  39145. };
  39146. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  39147. _this.inputs.addKeyboard().addMouse();
  39148. return _this;
  39149. }
  39150. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  39151. //-- begin properties for backward compatibility for inputs
  39152. get: function () {
  39153. var mouse = this.inputs.attached["mouse"];
  39154. if (mouse)
  39155. return mouse.angularSensibility;
  39156. return 0;
  39157. },
  39158. set: function (value) {
  39159. var mouse = this.inputs.attached["mouse"];
  39160. if (mouse)
  39161. mouse.angularSensibility = value;
  39162. },
  39163. enumerable: true,
  39164. configurable: true
  39165. });
  39166. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  39167. get: function () {
  39168. var keyboard = this.inputs.attached["keyboard"];
  39169. if (keyboard)
  39170. return keyboard.keysUp;
  39171. return [];
  39172. },
  39173. set: function (value) {
  39174. var keyboard = this.inputs.attached["keyboard"];
  39175. if (keyboard)
  39176. keyboard.keysUp = value;
  39177. },
  39178. enumerable: true,
  39179. configurable: true
  39180. });
  39181. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  39182. get: function () {
  39183. var keyboard = this.inputs.attached["keyboard"];
  39184. if (keyboard)
  39185. return keyboard.keysDown;
  39186. return [];
  39187. },
  39188. set: function (value) {
  39189. var keyboard = this.inputs.attached["keyboard"];
  39190. if (keyboard)
  39191. keyboard.keysDown = value;
  39192. },
  39193. enumerable: true,
  39194. configurable: true
  39195. });
  39196. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  39197. get: function () {
  39198. var keyboard = this.inputs.attached["keyboard"];
  39199. if (keyboard)
  39200. return keyboard.keysLeft;
  39201. return [];
  39202. },
  39203. set: function (value) {
  39204. var keyboard = this.inputs.attached["keyboard"];
  39205. if (keyboard)
  39206. keyboard.keysLeft = value;
  39207. },
  39208. enumerable: true,
  39209. configurable: true
  39210. });
  39211. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  39212. get: function () {
  39213. var keyboard = this.inputs.attached["keyboard"];
  39214. if (keyboard)
  39215. return keyboard.keysRight;
  39216. return [];
  39217. },
  39218. set: function (value) {
  39219. var keyboard = this.inputs.attached["keyboard"];
  39220. if (keyboard)
  39221. keyboard.keysRight = value;
  39222. },
  39223. enumerable: true,
  39224. configurable: true
  39225. });
  39226. // Controls
  39227. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  39228. this.inputs.attachElement(element, noPreventDefault);
  39229. };
  39230. FreeCamera.prototype.detachControl = function (element) {
  39231. this.inputs.detachElement(element);
  39232. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  39233. this.cameraRotation = new BABYLON.Vector2(0, 0);
  39234. };
  39235. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  39236. get: function () {
  39237. return this._collisionMask;
  39238. },
  39239. set: function (mask) {
  39240. this._collisionMask = !isNaN(mask) ? mask : -1;
  39241. },
  39242. enumerable: true,
  39243. configurable: true
  39244. });
  39245. FreeCamera.prototype._collideWithWorld = function (displacement) {
  39246. var globalPosition;
  39247. if (this.parent) {
  39248. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  39249. }
  39250. else {
  39251. globalPosition = this.position;
  39252. }
  39253. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  39254. this._oldPosition.addInPlace(this.ellipsoidOffset);
  39255. if (!this._collider) {
  39256. this._collider = new BABYLON.Collider();
  39257. }
  39258. this._collider._radius = this.ellipsoid;
  39259. this._collider.collisionMask = this._collisionMask;
  39260. //no need for clone, as long as gravity is not on.
  39261. var actualDisplacement = displacement;
  39262. //add gravity to the direction to prevent the dual-collision checking
  39263. if (this.applyGravity) {
  39264. //this prevents mending with cameraDirection, a global variable of the free camera class.
  39265. actualDisplacement = displacement.add(this.getScene().gravity);
  39266. }
  39267. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  39268. };
  39269. FreeCamera.prototype._checkInputs = function () {
  39270. if (!this._localDirection) {
  39271. this._localDirection = BABYLON.Vector3.Zero();
  39272. this._transformedDirection = BABYLON.Vector3.Zero();
  39273. }
  39274. this.inputs.checkInputs();
  39275. _super.prototype._checkInputs.call(this);
  39276. };
  39277. FreeCamera.prototype._decideIfNeedsToMove = function () {
  39278. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  39279. };
  39280. FreeCamera.prototype._updatePosition = function () {
  39281. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  39282. this._collideWithWorld(this.cameraDirection);
  39283. }
  39284. else {
  39285. _super.prototype._updatePosition.call(this);
  39286. }
  39287. };
  39288. FreeCamera.prototype.dispose = function () {
  39289. this.inputs.clear();
  39290. _super.prototype.dispose.call(this);
  39291. };
  39292. FreeCamera.prototype.getClassName = function () {
  39293. return "FreeCamera";
  39294. };
  39295. __decorate([
  39296. BABYLON.serializeAsVector3()
  39297. ], FreeCamera.prototype, "ellipsoid", void 0);
  39298. __decorate([
  39299. BABYLON.serializeAsVector3()
  39300. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  39301. __decorate([
  39302. BABYLON.serialize()
  39303. ], FreeCamera.prototype, "checkCollisions", void 0);
  39304. __decorate([
  39305. BABYLON.serialize()
  39306. ], FreeCamera.prototype, "applyGravity", void 0);
  39307. return FreeCamera;
  39308. }(BABYLON.TargetCamera));
  39309. BABYLON.FreeCamera = FreeCamera;
  39310. })(BABYLON || (BABYLON = {}));
  39311. //# sourceMappingURL=babylon.freeCamera.js.map
  39312. var BABYLON;
  39313. (function (BABYLON) {
  39314. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  39315. function ArcRotateCameraKeyboardMoveInput() {
  39316. this._keys = new Array();
  39317. this.keysUp = [38];
  39318. this.keysDown = [40];
  39319. this.keysLeft = [37];
  39320. this.keysRight = [39];
  39321. this.keysReset = [220];
  39322. this.panningSensibility = 50.0;
  39323. this.zoomingSensibility = 25.0;
  39324. this.useAltToZoom = true;
  39325. }
  39326. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  39327. var _this = this;
  39328. if (this._onCanvasBlurObserver) {
  39329. return;
  39330. }
  39331. this._scene = this.camera.getScene();
  39332. this._engine = this._scene.getEngine();
  39333. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  39334. _this._keys = [];
  39335. });
  39336. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  39337. var evt = info.event;
  39338. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  39339. _this._ctrlPressed = evt.ctrlKey;
  39340. _this._altPressed = evt.altKey;
  39341. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  39342. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  39343. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  39344. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  39345. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  39346. var index = _this._keys.indexOf(evt.keyCode);
  39347. if (index === -1) {
  39348. _this._keys.push(evt.keyCode);
  39349. }
  39350. if (evt.preventDefault) {
  39351. if (!noPreventDefault) {
  39352. evt.preventDefault();
  39353. }
  39354. }
  39355. }
  39356. }
  39357. else {
  39358. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  39359. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  39360. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  39361. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  39362. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  39363. var index = _this._keys.indexOf(evt.keyCode);
  39364. if (index >= 0) {
  39365. _this._keys.splice(index, 1);
  39366. }
  39367. if (evt.preventDefault) {
  39368. if (!noPreventDefault) {
  39369. evt.preventDefault();
  39370. }
  39371. }
  39372. }
  39373. }
  39374. });
  39375. };
  39376. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  39377. if (this._scene) {
  39378. if (this._onKeyboardObserver) {
  39379. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  39380. }
  39381. if (this._onCanvasBlurObserver) {
  39382. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  39383. }
  39384. this._onKeyboardObserver = null;
  39385. this._onCanvasBlurObserver = null;
  39386. }
  39387. this._keys = [];
  39388. };
  39389. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  39390. if (this._onKeyboardObserver) {
  39391. var camera = this.camera;
  39392. for (var index = 0; index < this._keys.length; index++) {
  39393. var keyCode = this._keys[index];
  39394. if (this.keysLeft.indexOf(keyCode) !== -1) {
  39395. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  39396. camera.inertialPanningX -= 1 / this.panningSensibility;
  39397. }
  39398. else {
  39399. camera.inertialAlphaOffset -= 0.01;
  39400. }
  39401. }
  39402. else if (this.keysUp.indexOf(keyCode) !== -1) {
  39403. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  39404. camera.inertialPanningY += 1 / this.panningSensibility;
  39405. }
  39406. else if (this._altPressed && this.useAltToZoom) {
  39407. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  39408. }
  39409. else {
  39410. camera.inertialBetaOffset -= 0.01;
  39411. }
  39412. }
  39413. else if (this.keysRight.indexOf(keyCode) !== -1) {
  39414. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  39415. camera.inertialPanningX += 1 / this.panningSensibility;
  39416. }
  39417. else {
  39418. camera.inertialAlphaOffset += 0.01;
  39419. }
  39420. }
  39421. else if (this.keysDown.indexOf(keyCode) !== -1) {
  39422. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  39423. camera.inertialPanningY -= 1 / this.panningSensibility;
  39424. }
  39425. else if (this._altPressed && this.useAltToZoom) {
  39426. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  39427. }
  39428. else {
  39429. camera.inertialBetaOffset += 0.01;
  39430. }
  39431. }
  39432. else if (this.keysReset.indexOf(keyCode) !== -1) {
  39433. camera.restoreState();
  39434. }
  39435. }
  39436. }
  39437. };
  39438. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  39439. return "ArcRotateCameraKeyboardMoveInput";
  39440. };
  39441. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  39442. return "keyboard";
  39443. };
  39444. __decorate([
  39445. BABYLON.serialize()
  39446. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  39447. __decorate([
  39448. BABYLON.serialize()
  39449. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  39450. __decorate([
  39451. BABYLON.serialize()
  39452. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  39453. __decorate([
  39454. BABYLON.serialize()
  39455. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  39456. __decorate([
  39457. BABYLON.serialize()
  39458. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  39459. __decorate([
  39460. BABYLON.serialize()
  39461. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  39462. __decorate([
  39463. BABYLON.serialize()
  39464. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  39465. __decorate([
  39466. BABYLON.serialize()
  39467. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  39468. return ArcRotateCameraKeyboardMoveInput;
  39469. }());
  39470. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  39471. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  39472. })(BABYLON || (BABYLON = {}));
  39473. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  39474. var BABYLON;
  39475. (function (BABYLON) {
  39476. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  39477. function ArcRotateCameraMouseWheelInput() {
  39478. this.wheelPrecision = 3.0;
  39479. /**
  39480. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  39481. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  39482. */
  39483. this.wheelDeltaPercentage = 0;
  39484. }
  39485. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  39486. var _this = this;
  39487. this._wheel = function (p, s) {
  39488. //sanity check - this should be a PointerWheel event.
  39489. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  39490. return;
  39491. var event = p.event;
  39492. var delta = 0;
  39493. if (event.wheelDelta) {
  39494. delta = _this.wheelDeltaPercentage ? (event.wheelDelta * 0.01) * _this.camera.radius * _this.wheelDeltaPercentage : event.wheelDelta / (_this.wheelPrecision * 40);
  39495. }
  39496. else if (event.detail) {
  39497. delta = -event.detail / _this.wheelPrecision;
  39498. }
  39499. if (delta)
  39500. _this.camera.inertialRadiusOffset += delta;
  39501. if (event.preventDefault) {
  39502. if (!noPreventDefault) {
  39503. event.preventDefault();
  39504. }
  39505. }
  39506. };
  39507. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  39508. };
  39509. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  39510. if (this._observer && element) {
  39511. this.camera.getScene().onPointerObservable.remove(this._observer);
  39512. this._observer = null;
  39513. this._wheel = null;
  39514. }
  39515. };
  39516. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  39517. return "ArcRotateCameraMouseWheelInput";
  39518. };
  39519. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  39520. return "mousewheel";
  39521. };
  39522. __decorate([
  39523. BABYLON.serialize()
  39524. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  39525. __decorate([
  39526. BABYLON.serialize()
  39527. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  39528. return ArcRotateCameraMouseWheelInput;
  39529. }());
  39530. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  39531. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  39532. })(BABYLON || (BABYLON = {}));
  39533. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  39534. var BABYLON;
  39535. (function (BABYLON) {
  39536. var ArcRotateCameraPointersInput = /** @class */ (function () {
  39537. function ArcRotateCameraPointersInput() {
  39538. this.buttons = [0, 1, 2];
  39539. this.angularSensibilityX = 1000.0;
  39540. this.angularSensibilityY = 1000.0;
  39541. this.pinchPrecision = 12.0;
  39542. /**
  39543. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  39544. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  39545. */
  39546. this.pinchDeltaPercentage = 0;
  39547. this.panningSensibility = 1000.0;
  39548. this.multiTouchPanning = true;
  39549. this.multiTouchPanAndZoom = true;
  39550. this._isPanClick = false;
  39551. this.pinchInwards = true;
  39552. }
  39553. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  39554. var _this = this;
  39555. var engine = this.camera.getEngine();
  39556. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  39557. var pointA = null;
  39558. var pointB = null;
  39559. var previousPinchSquaredDistance = 0;
  39560. var initialDistance = 0;
  39561. var twoFingerActivityCount = 0;
  39562. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  39563. this._pointerInput = function (p, s) {
  39564. var evt = p.event;
  39565. var isTouch = p.event.pointerType === "touch";
  39566. if (engine.isInVRExclusivePointerMode) {
  39567. return;
  39568. }
  39569. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  39570. return;
  39571. }
  39572. var srcElement = (evt.srcElement || evt.target);
  39573. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  39574. try {
  39575. srcElement.setPointerCapture(evt.pointerId);
  39576. }
  39577. catch (e) {
  39578. //Nothing to do with the error. Execution will continue.
  39579. }
  39580. // Manage panning with pan button click
  39581. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  39582. // manage pointers
  39583. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  39584. if (pointA === null) {
  39585. pointA = cacheSoloPointer;
  39586. }
  39587. else if (pointB === null) {
  39588. pointB = cacheSoloPointer;
  39589. }
  39590. if (!noPreventDefault) {
  39591. evt.preventDefault();
  39592. element.focus();
  39593. }
  39594. }
  39595. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  39596. _this.camera.restoreState();
  39597. }
  39598. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  39599. try {
  39600. srcElement.releasePointerCapture(evt.pointerId);
  39601. }
  39602. catch (e) {
  39603. //Nothing to do with the error.
  39604. }
  39605. cacheSoloPointer = null;
  39606. previousPinchSquaredDistance = 0;
  39607. previousMultiTouchPanPosition.isPaning = false;
  39608. previousMultiTouchPanPosition.isPinching = false;
  39609. twoFingerActivityCount = 0;
  39610. initialDistance = 0;
  39611. if (!isTouch) {
  39612. pointB = null; // Mouse and pen are mono pointer
  39613. }
  39614. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  39615. //but emptying completly pointers collection is required to fix a bug on iPhone :
  39616. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  39617. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  39618. if (engine.badOS) {
  39619. pointA = pointB = null;
  39620. }
  39621. else {
  39622. //only remove the impacted pointer in case of multitouch allowing on most
  39623. //platforms switching from rotate to zoom and pan seamlessly.
  39624. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  39625. pointA = pointB;
  39626. pointB = null;
  39627. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  39628. }
  39629. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  39630. pointB = null;
  39631. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  39632. }
  39633. else {
  39634. pointA = pointB = null;
  39635. }
  39636. }
  39637. if (!noPreventDefault) {
  39638. evt.preventDefault();
  39639. }
  39640. }
  39641. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  39642. if (!noPreventDefault) {
  39643. evt.preventDefault();
  39644. }
  39645. // One button down
  39646. if (pointA && pointB === null && cacheSoloPointer) {
  39647. if (_this.panningSensibility !== 0 &&
  39648. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  39649. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  39650. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  39651. }
  39652. else {
  39653. var offsetX = evt.clientX - cacheSoloPointer.x;
  39654. var offsetY = evt.clientY - cacheSoloPointer.y;
  39655. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  39656. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  39657. }
  39658. cacheSoloPointer.x = evt.clientX;
  39659. cacheSoloPointer.y = evt.clientY;
  39660. }
  39661. else if (pointA && pointB) {
  39662. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  39663. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  39664. ed.x = evt.clientX;
  39665. ed.y = evt.clientY;
  39666. var direction = _this.pinchInwards ? 1 : -1;
  39667. var distX = pointA.x - pointB.x;
  39668. var distY = pointA.y - pointB.y;
  39669. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  39670. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  39671. if (previousPinchSquaredDistance === 0) {
  39672. initialDistance = pinchDistance;
  39673. previousPinchSquaredDistance = pinchSquaredDistance;
  39674. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  39675. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  39676. return;
  39677. }
  39678. if (_this.multiTouchPanAndZoom) {
  39679. if (_this.pinchDeltaPercentage) {
  39680. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  39681. }
  39682. else {
  39683. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  39684. (_this.pinchPrecision *
  39685. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  39686. direction);
  39687. }
  39688. if (_this.panningSensibility !== 0) {
  39689. var pointersCenterX = (pointA.x + pointB.x) / 2;
  39690. var pointersCenterY = (pointA.y + pointB.y) / 2;
  39691. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  39692. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  39693. previousMultiTouchPanPosition.x = pointersCenterX;
  39694. previousMultiTouchPanPosition.y = pointersCenterY;
  39695. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  39696. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  39697. }
  39698. }
  39699. else {
  39700. twoFingerActivityCount++;
  39701. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  39702. if (_this.pinchDeltaPercentage) {
  39703. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  39704. }
  39705. else {
  39706. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  39707. (_this.pinchPrecision *
  39708. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  39709. direction);
  39710. }
  39711. previousMultiTouchPanPosition.isPaning = false;
  39712. previousMultiTouchPanPosition.isPinching = true;
  39713. }
  39714. else {
  39715. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  39716. if (!previousMultiTouchPanPosition.isPaning) {
  39717. previousMultiTouchPanPosition.isPaning = true;
  39718. previousMultiTouchPanPosition.isPinching = false;
  39719. previousMultiTouchPanPosition.x = ed.x;
  39720. previousMultiTouchPanPosition.y = ed.y;
  39721. return;
  39722. }
  39723. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  39724. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  39725. }
  39726. }
  39727. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  39728. previousMultiTouchPanPosition.x = ed.x;
  39729. previousMultiTouchPanPosition.y = ed.y;
  39730. }
  39731. }
  39732. previousPinchSquaredDistance = pinchSquaredDistance;
  39733. }
  39734. }
  39735. };
  39736. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  39737. this._onContextMenu = function (evt) {
  39738. evt.preventDefault();
  39739. };
  39740. if (!this.camera._useCtrlForPanning) {
  39741. element.addEventListener("contextmenu", this._onContextMenu, false);
  39742. }
  39743. this._onLostFocus = function () {
  39744. //this._keys = [];
  39745. pointA = pointB = null;
  39746. previousPinchSquaredDistance = 0;
  39747. previousMultiTouchPanPosition.isPaning = false;
  39748. previousMultiTouchPanPosition.isPinching = false;
  39749. twoFingerActivityCount = 0;
  39750. cacheSoloPointer = null;
  39751. initialDistance = 0;
  39752. };
  39753. this._onMouseMove = function (evt) {
  39754. if (!engine.isPointerLock) {
  39755. return;
  39756. }
  39757. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  39758. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  39759. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  39760. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  39761. if (!noPreventDefault) {
  39762. evt.preventDefault();
  39763. }
  39764. };
  39765. this._onGestureStart = function (e) {
  39766. if (window.MSGesture === undefined) {
  39767. return;
  39768. }
  39769. if (!_this._MSGestureHandler) {
  39770. _this._MSGestureHandler = new MSGesture();
  39771. _this._MSGestureHandler.target = element;
  39772. }
  39773. _this._MSGestureHandler.addPointer(e.pointerId);
  39774. };
  39775. this._onGesture = function (e) {
  39776. _this.camera.radius *= e.scale;
  39777. if (e.preventDefault) {
  39778. if (!noPreventDefault) {
  39779. e.stopPropagation();
  39780. e.preventDefault();
  39781. }
  39782. }
  39783. };
  39784. element.addEventListener("mousemove", this._onMouseMove, false);
  39785. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  39786. element.addEventListener("MSGestureChange", this._onGesture, false);
  39787. BABYLON.Tools.RegisterTopRootEvents([
  39788. { name: "blur", handler: this._onLostFocus }
  39789. ]);
  39790. };
  39791. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  39792. if (this._onLostFocus) {
  39793. BABYLON.Tools.UnregisterTopRootEvents([
  39794. { name: "blur", handler: this._onLostFocus }
  39795. ]);
  39796. }
  39797. if (element && this._observer) {
  39798. this.camera.getScene().onPointerObservable.remove(this._observer);
  39799. this._observer = null;
  39800. if (this._onContextMenu) {
  39801. element.removeEventListener("contextmenu", this._onContextMenu);
  39802. }
  39803. if (this._onMouseMove) {
  39804. element.removeEventListener("mousemove", this._onMouseMove);
  39805. }
  39806. if (this._onGestureStart) {
  39807. element.removeEventListener("MSPointerDown", this._onGestureStart);
  39808. }
  39809. if (this._onGesture) {
  39810. element.removeEventListener("MSGestureChange", this._onGesture);
  39811. }
  39812. this._isPanClick = false;
  39813. this.pinchInwards = true;
  39814. this._onMouseMove = null;
  39815. this._onGestureStart = null;
  39816. this._onGesture = null;
  39817. this._MSGestureHandler = null;
  39818. this._onLostFocus = null;
  39819. this._onContextMenu = null;
  39820. }
  39821. };
  39822. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  39823. return "ArcRotateCameraPointersInput";
  39824. };
  39825. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  39826. return "pointers";
  39827. };
  39828. __decorate([
  39829. BABYLON.serialize()
  39830. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  39831. __decorate([
  39832. BABYLON.serialize()
  39833. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  39834. __decorate([
  39835. BABYLON.serialize()
  39836. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  39837. __decorate([
  39838. BABYLON.serialize()
  39839. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  39840. __decorate([
  39841. BABYLON.serialize()
  39842. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  39843. __decorate([
  39844. BABYLON.serialize()
  39845. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  39846. __decorate([
  39847. BABYLON.serialize()
  39848. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  39849. __decorate([
  39850. BABYLON.serialize()
  39851. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  39852. return ArcRotateCameraPointersInput;
  39853. }());
  39854. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  39855. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  39856. })(BABYLON || (BABYLON = {}));
  39857. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  39858. var BABYLON;
  39859. (function (BABYLON) {
  39860. var ArcRotateCamera = /** @class */ (function (_super) {
  39861. __extends(ArcRotateCamera, _super);
  39862. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  39863. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  39864. _this.inertialAlphaOffset = 0;
  39865. _this.inertialBetaOffset = 0;
  39866. _this.inertialRadiusOffset = 0;
  39867. _this.lowerAlphaLimit = null;
  39868. _this.upperAlphaLimit = null;
  39869. _this.lowerBetaLimit = 0.01;
  39870. _this.upperBetaLimit = Math.PI;
  39871. _this.lowerRadiusLimit = null;
  39872. _this.upperRadiusLimit = null;
  39873. _this.inertialPanningX = 0;
  39874. _this.inertialPanningY = 0;
  39875. _this.pinchToPanMaxDistance = 20;
  39876. _this.panningDistanceLimit = null;
  39877. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  39878. _this.panningInertia = 0.9;
  39879. //-- end properties for backward compatibility for inputs
  39880. _this.zoomOnFactor = 1;
  39881. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  39882. _this.allowUpsideDown = true;
  39883. _this._viewMatrix = new BABYLON.Matrix();
  39884. // Panning
  39885. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  39886. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  39887. _this.checkCollisions = false;
  39888. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  39889. _this._previousPosition = BABYLON.Vector3.Zero();
  39890. _this._collisionVelocity = BABYLON.Vector3.Zero();
  39891. _this._newPosition = BABYLON.Vector3.Zero();
  39892. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  39893. if (collidedMesh === void 0) { collidedMesh = null; }
  39894. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  39895. newPosition.multiplyInPlace(_this._collider._radius);
  39896. }
  39897. if (!collidedMesh) {
  39898. _this._previousPosition.copyFrom(_this.position);
  39899. }
  39900. else {
  39901. _this.setPosition(newPosition);
  39902. if (_this.onCollide) {
  39903. _this.onCollide(collidedMesh);
  39904. }
  39905. }
  39906. // Recompute because of constraints
  39907. var cosa = Math.cos(_this.alpha);
  39908. var sina = Math.sin(_this.alpha);
  39909. var cosb = Math.cos(_this.beta);
  39910. var sinb = Math.sin(_this.beta);
  39911. if (sinb === 0) {
  39912. sinb = 0.0001;
  39913. }
  39914. var target = _this._getTargetPosition();
  39915. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  39916. _this.position.copyFrom(_this._newPosition);
  39917. var up = _this.upVector;
  39918. if (_this.allowUpsideDown && _this.beta < 0) {
  39919. up = up.clone();
  39920. up = up.negate();
  39921. }
  39922. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  39923. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  39924. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  39925. _this._collisionTriggered = false;
  39926. };
  39927. _this._target = BABYLON.Vector3.Zero();
  39928. if (target) {
  39929. _this.setTarget(target);
  39930. }
  39931. _this.alpha = alpha;
  39932. _this.beta = beta;
  39933. _this.radius = radius;
  39934. _this.getViewMatrix();
  39935. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  39936. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  39937. return _this;
  39938. }
  39939. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  39940. get: function () {
  39941. return this._target;
  39942. },
  39943. set: function (value) {
  39944. this.setTarget(value);
  39945. },
  39946. enumerable: true,
  39947. configurable: true
  39948. });
  39949. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  39950. //-- begin properties for backward compatibility for inputs
  39951. get: function () {
  39952. var pointers = this.inputs.attached["pointers"];
  39953. if (pointers)
  39954. return pointers.angularSensibilityX;
  39955. return 0;
  39956. },
  39957. set: function (value) {
  39958. var pointers = this.inputs.attached["pointers"];
  39959. if (pointers) {
  39960. pointers.angularSensibilityX = value;
  39961. }
  39962. },
  39963. enumerable: true,
  39964. configurable: true
  39965. });
  39966. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  39967. get: function () {
  39968. var pointers = this.inputs.attached["pointers"];
  39969. if (pointers)
  39970. return pointers.angularSensibilityY;
  39971. return 0;
  39972. },
  39973. set: function (value) {
  39974. var pointers = this.inputs.attached["pointers"];
  39975. if (pointers) {
  39976. pointers.angularSensibilityY = value;
  39977. }
  39978. },
  39979. enumerable: true,
  39980. configurable: true
  39981. });
  39982. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  39983. get: function () {
  39984. var pointers = this.inputs.attached["pointers"];
  39985. if (pointers)
  39986. return pointers.pinchPrecision;
  39987. return 0;
  39988. },
  39989. set: function (value) {
  39990. var pointers = this.inputs.attached["pointers"];
  39991. if (pointers) {
  39992. pointers.pinchPrecision = value;
  39993. }
  39994. },
  39995. enumerable: true,
  39996. configurable: true
  39997. });
  39998. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  39999. get: function () {
  40000. var pointers = this.inputs.attached["pointers"];
  40001. if (pointers)
  40002. return pointers.pinchDeltaPercentage;
  40003. return 0;
  40004. },
  40005. set: function (value) {
  40006. var pointers = this.inputs.attached["pointers"];
  40007. if (pointers) {
  40008. pointers.pinchDeltaPercentage = value;
  40009. }
  40010. },
  40011. enumerable: true,
  40012. configurable: true
  40013. });
  40014. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  40015. get: function () {
  40016. var pointers = this.inputs.attached["pointers"];
  40017. if (pointers)
  40018. return pointers.panningSensibility;
  40019. return 0;
  40020. },
  40021. set: function (value) {
  40022. var pointers = this.inputs.attached["pointers"];
  40023. if (pointers) {
  40024. pointers.panningSensibility = value;
  40025. }
  40026. },
  40027. enumerable: true,
  40028. configurable: true
  40029. });
  40030. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  40031. get: function () {
  40032. var keyboard = this.inputs.attached["keyboard"];
  40033. if (keyboard)
  40034. return keyboard.keysUp;
  40035. return [];
  40036. },
  40037. set: function (value) {
  40038. var keyboard = this.inputs.attached["keyboard"];
  40039. if (keyboard)
  40040. keyboard.keysUp = value;
  40041. },
  40042. enumerable: true,
  40043. configurable: true
  40044. });
  40045. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  40046. get: function () {
  40047. var keyboard = this.inputs.attached["keyboard"];
  40048. if (keyboard)
  40049. return keyboard.keysDown;
  40050. return [];
  40051. },
  40052. set: function (value) {
  40053. var keyboard = this.inputs.attached["keyboard"];
  40054. if (keyboard)
  40055. keyboard.keysDown = value;
  40056. },
  40057. enumerable: true,
  40058. configurable: true
  40059. });
  40060. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  40061. get: function () {
  40062. var keyboard = this.inputs.attached["keyboard"];
  40063. if (keyboard)
  40064. return keyboard.keysLeft;
  40065. return [];
  40066. },
  40067. set: function (value) {
  40068. var keyboard = this.inputs.attached["keyboard"];
  40069. if (keyboard)
  40070. keyboard.keysLeft = value;
  40071. },
  40072. enumerable: true,
  40073. configurable: true
  40074. });
  40075. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  40076. get: function () {
  40077. var keyboard = this.inputs.attached["keyboard"];
  40078. if (keyboard)
  40079. return keyboard.keysRight;
  40080. return [];
  40081. },
  40082. set: function (value) {
  40083. var keyboard = this.inputs.attached["keyboard"];
  40084. if (keyboard)
  40085. keyboard.keysRight = value;
  40086. },
  40087. enumerable: true,
  40088. configurable: true
  40089. });
  40090. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  40091. get: function () {
  40092. var mousewheel = this.inputs.attached["mousewheel"];
  40093. if (mousewheel)
  40094. return mousewheel.wheelPrecision;
  40095. return 0;
  40096. },
  40097. set: function (value) {
  40098. var mousewheel = this.inputs.attached["mousewheel"];
  40099. if (mousewheel)
  40100. mousewheel.wheelPrecision = value;
  40101. },
  40102. enumerable: true,
  40103. configurable: true
  40104. });
  40105. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  40106. get: function () {
  40107. var mousewheel = this.inputs.attached["mousewheel"];
  40108. if (mousewheel)
  40109. return mousewheel.wheelDeltaPercentage;
  40110. return 0;
  40111. },
  40112. set: function (value) {
  40113. var mousewheel = this.inputs.attached["mousewheel"];
  40114. if (mousewheel)
  40115. mousewheel.wheelDeltaPercentage = value;
  40116. },
  40117. enumerable: true,
  40118. configurable: true
  40119. });
  40120. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  40121. get: function () {
  40122. return this._bouncingBehavior;
  40123. },
  40124. enumerable: true,
  40125. configurable: true
  40126. });
  40127. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  40128. get: function () {
  40129. return this._bouncingBehavior != null;
  40130. },
  40131. set: function (value) {
  40132. if (value === this.useBouncingBehavior) {
  40133. return;
  40134. }
  40135. if (value) {
  40136. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  40137. this.addBehavior(this._bouncingBehavior);
  40138. }
  40139. else if (this._bouncingBehavior) {
  40140. this.removeBehavior(this._bouncingBehavior);
  40141. this._bouncingBehavior = null;
  40142. }
  40143. },
  40144. enumerable: true,
  40145. configurable: true
  40146. });
  40147. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  40148. get: function () {
  40149. return this._framingBehavior;
  40150. },
  40151. enumerable: true,
  40152. configurable: true
  40153. });
  40154. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  40155. get: function () {
  40156. return this._framingBehavior != null;
  40157. },
  40158. set: function (value) {
  40159. if (value === this.useFramingBehavior) {
  40160. return;
  40161. }
  40162. if (value) {
  40163. this._framingBehavior = new BABYLON.FramingBehavior();
  40164. this.addBehavior(this._framingBehavior);
  40165. }
  40166. else if (this._framingBehavior) {
  40167. this.removeBehavior(this._framingBehavior);
  40168. this._framingBehavior = null;
  40169. }
  40170. },
  40171. enumerable: true,
  40172. configurable: true
  40173. });
  40174. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  40175. get: function () {
  40176. return this._autoRotationBehavior;
  40177. },
  40178. enumerable: true,
  40179. configurable: true
  40180. });
  40181. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  40182. get: function () {
  40183. return this._autoRotationBehavior != null;
  40184. },
  40185. set: function (value) {
  40186. if (value === this.useAutoRotationBehavior) {
  40187. return;
  40188. }
  40189. if (value) {
  40190. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  40191. this.addBehavior(this._autoRotationBehavior);
  40192. }
  40193. else if (this._autoRotationBehavior) {
  40194. this.removeBehavior(this._autoRotationBehavior);
  40195. this._autoRotationBehavior = null;
  40196. }
  40197. },
  40198. enumerable: true,
  40199. configurable: true
  40200. });
  40201. // Cache
  40202. ArcRotateCamera.prototype._initCache = function () {
  40203. _super.prototype._initCache.call(this);
  40204. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  40205. this._cache.alpha = undefined;
  40206. this._cache.beta = undefined;
  40207. this._cache.radius = undefined;
  40208. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  40209. };
  40210. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  40211. if (!ignoreParentClass) {
  40212. _super.prototype._updateCache.call(this);
  40213. }
  40214. this._cache._target.copyFrom(this._getTargetPosition());
  40215. this._cache.alpha = this.alpha;
  40216. this._cache.beta = this.beta;
  40217. this._cache.radius = this.radius;
  40218. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  40219. };
  40220. ArcRotateCamera.prototype._getTargetPosition = function () {
  40221. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  40222. var pos = this._targetHost.getAbsolutePosition();
  40223. if (this._targetBoundingCenter) {
  40224. pos.addToRef(this._targetBoundingCenter, this._target);
  40225. }
  40226. else {
  40227. this._target.copyFrom(pos);
  40228. }
  40229. }
  40230. var lockedTargetPosition = this._getLockedTargetPosition();
  40231. if (lockedTargetPosition) {
  40232. return lockedTargetPosition;
  40233. }
  40234. return this._target;
  40235. };
  40236. ArcRotateCamera.prototype.storeState = function () {
  40237. this._storedAlpha = this.alpha;
  40238. this._storedBeta = this.beta;
  40239. this._storedRadius = this.radius;
  40240. this._storedTarget = this._getTargetPosition().clone();
  40241. return _super.prototype.storeState.call(this);
  40242. };
  40243. /**
  40244. * Restored camera state. You must call storeState() first
  40245. */
  40246. ArcRotateCamera.prototype._restoreStateValues = function () {
  40247. if (!_super.prototype._restoreStateValues.call(this)) {
  40248. return false;
  40249. }
  40250. this.alpha = this._storedAlpha;
  40251. this.beta = this._storedBeta;
  40252. this.radius = this._storedRadius;
  40253. this.setTarget(this._storedTarget.clone());
  40254. this.inertialAlphaOffset = 0;
  40255. this.inertialBetaOffset = 0;
  40256. this.inertialRadiusOffset = 0;
  40257. this.inertialPanningX = 0;
  40258. this.inertialPanningY = 0;
  40259. return true;
  40260. };
  40261. // Synchronized
  40262. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  40263. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  40264. return false;
  40265. return this._cache._target.equals(this._getTargetPosition())
  40266. && this._cache.alpha === this.alpha
  40267. && this._cache.beta === this.beta
  40268. && this._cache.radius === this.radius
  40269. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  40270. };
  40271. // Methods
  40272. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  40273. var _this = this;
  40274. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  40275. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  40276. this._useCtrlForPanning = useCtrlForPanning;
  40277. this._panningMouseButton = panningMouseButton;
  40278. this.inputs.attachElement(element, noPreventDefault);
  40279. this._reset = function () {
  40280. _this.inertialAlphaOffset = 0;
  40281. _this.inertialBetaOffset = 0;
  40282. _this.inertialRadiusOffset = 0;
  40283. _this.inertialPanningX = 0;
  40284. _this.inertialPanningY = 0;
  40285. };
  40286. };
  40287. ArcRotateCamera.prototype.detachControl = function (element) {
  40288. this.inputs.detachElement(element);
  40289. if (this._reset) {
  40290. this._reset();
  40291. }
  40292. };
  40293. ArcRotateCamera.prototype._checkInputs = function () {
  40294. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  40295. if (this._collisionTriggered) {
  40296. return;
  40297. }
  40298. this.inputs.checkInputs();
  40299. // Inertia
  40300. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  40301. if (this.getScene().useRightHandedSystem) {
  40302. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  40303. }
  40304. else {
  40305. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  40306. }
  40307. this.beta += this.inertialBetaOffset;
  40308. this.radius -= this.inertialRadiusOffset;
  40309. this.inertialAlphaOffset *= this.inertia;
  40310. this.inertialBetaOffset *= this.inertia;
  40311. this.inertialRadiusOffset *= this.inertia;
  40312. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  40313. this.inertialAlphaOffset = 0;
  40314. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  40315. this.inertialBetaOffset = 0;
  40316. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  40317. this.inertialRadiusOffset = 0;
  40318. }
  40319. // Panning inertia
  40320. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  40321. if (!this._localDirection) {
  40322. this._localDirection = BABYLON.Vector3.Zero();
  40323. this._transformedDirection = BABYLON.Vector3.Zero();
  40324. }
  40325. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  40326. this._localDirection.multiplyInPlace(this.panningAxis);
  40327. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  40328. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  40329. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  40330. if (!this.panningAxis.y) {
  40331. this._transformedDirection.y = 0;
  40332. }
  40333. if (!this._targetHost) {
  40334. if (this.panningDistanceLimit) {
  40335. this._transformedDirection.addInPlace(this._target);
  40336. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  40337. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  40338. this._target.copyFrom(this._transformedDirection);
  40339. }
  40340. }
  40341. else {
  40342. this._target.addInPlace(this._transformedDirection);
  40343. }
  40344. }
  40345. this.inertialPanningX *= this.panningInertia;
  40346. this.inertialPanningY *= this.panningInertia;
  40347. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  40348. this.inertialPanningX = 0;
  40349. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  40350. this.inertialPanningY = 0;
  40351. }
  40352. // Limits
  40353. this._checkLimits();
  40354. _super.prototype._checkInputs.call(this);
  40355. };
  40356. ArcRotateCamera.prototype._checkLimits = function () {
  40357. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  40358. if (this.allowUpsideDown && this.beta > Math.PI) {
  40359. this.beta = this.beta - (2 * Math.PI);
  40360. }
  40361. }
  40362. else {
  40363. if (this.beta < this.lowerBetaLimit) {
  40364. this.beta = this.lowerBetaLimit;
  40365. }
  40366. }
  40367. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  40368. if (this.allowUpsideDown && this.beta < -Math.PI) {
  40369. this.beta = this.beta + (2 * Math.PI);
  40370. }
  40371. }
  40372. else {
  40373. if (this.beta > this.upperBetaLimit) {
  40374. this.beta = this.upperBetaLimit;
  40375. }
  40376. }
  40377. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  40378. this.alpha = this.lowerAlphaLimit;
  40379. }
  40380. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  40381. this.alpha = this.upperAlphaLimit;
  40382. }
  40383. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  40384. this.radius = this.lowerRadiusLimit;
  40385. }
  40386. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  40387. this.radius = this.upperRadiusLimit;
  40388. }
  40389. };
  40390. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  40391. var radiusv3 = this.position.subtract(this._getTargetPosition());
  40392. this.radius = radiusv3.length();
  40393. if (this.radius === 0) {
  40394. this.radius = 0.0001; // Just to avoid division by zero
  40395. }
  40396. // Alpha
  40397. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  40398. if (radiusv3.z < 0) {
  40399. this.alpha = 2 * Math.PI - this.alpha;
  40400. }
  40401. // Beta
  40402. this.beta = Math.acos(radiusv3.y / this.radius);
  40403. this._checkLimits();
  40404. };
  40405. ArcRotateCamera.prototype.setPosition = function (position) {
  40406. if (this.position.equals(position)) {
  40407. return;
  40408. }
  40409. this.position.copyFrom(position);
  40410. this.rebuildAnglesAndRadius();
  40411. };
  40412. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  40413. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  40414. if (allowSamePosition === void 0) { allowSamePosition = false; }
  40415. if (target.getBoundingInfo) {
  40416. if (toBoundingCenter) {
  40417. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  40418. }
  40419. else {
  40420. this._targetBoundingCenter = null;
  40421. }
  40422. this._targetHost = target;
  40423. this._target = this._getTargetPosition();
  40424. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  40425. }
  40426. else {
  40427. var newTarget = target;
  40428. var currentTarget = this._getTargetPosition();
  40429. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  40430. return;
  40431. }
  40432. this._targetHost = null;
  40433. this._target = newTarget;
  40434. this._targetBoundingCenter = null;
  40435. this.onMeshTargetChangedObservable.notifyObservers(null);
  40436. }
  40437. this.rebuildAnglesAndRadius();
  40438. };
  40439. ArcRotateCamera.prototype._getViewMatrix = function () {
  40440. // Compute
  40441. var cosa = Math.cos(this.alpha);
  40442. var sina = Math.sin(this.alpha);
  40443. var cosb = Math.cos(this.beta);
  40444. var sinb = Math.sin(this.beta);
  40445. if (sinb === 0) {
  40446. sinb = 0.0001;
  40447. }
  40448. var target = this._getTargetPosition();
  40449. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  40450. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  40451. if (!this._collider) {
  40452. this._collider = new BABYLON.Collider();
  40453. }
  40454. this._collider._radius = this.collisionRadius;
  40455. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  40456. this._collisionTriggered = true;
  40457. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  40458. }
  40459. else {
  40460. this.position.copyFrom(this._newPosition);
  40461. var up = this.upVector;
  40462. if (this.allowUpsideDown && sinb < 0) {
  40463. up = up.clone();
  40464. up = up.negate();
  40465. }
  40466. if (this.getScene().useRightHandedSystem) {
  40467. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  40468. }
  40469. else {
  40470. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  40471. }
  40472. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  40473. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  40474. }
  40475. this._currentTarget = target;
  40476. return this._viewMatrix;
  40477. };
  40478. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  40479. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  40480. meshes = meshes || this.getScene().meshes;
  40481. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  40482. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  40483. this.radius = distance * this.zoomOnFactor;
  40484. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  40485. };
  40486. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  40487. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  40488. var meshesOrMinMaxVector;
  40489. var distance;
  40490. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  40491. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  40492. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  40493. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  40494. }
  40495. else {
  40496. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  40497. meshesOrMinMaxVector = minMaxVectorAndDistance;
  40498. distance = minMaxVectorAndDistance.distance;
  40499. }
  40500. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  40501. if (!doNotUpdateMaxZ) {
  40502. this.maxZ = distance * 2;
  40503. }
  40504. };
  40505. /**
  40506. * @override
  40507. * Override Camera.createRigCamera
  40508. */
  40509. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  40510. var alphaShift = 0;
  40511. switch (this.cameraRigMode) {
  40512. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  40513. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  40514. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  40515. case BABYLON.Camera.RIG_MODE_VR:
  40516. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  40517. break;
  40518. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  40519. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  40520. break;
  40521. }
  40522. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  40523. rigCam._cameraRigParams = {};
  40524. return rigCam;
  40525. };
  40526. /**
  40527. * @override
  40528. * Override Camera._updateRigCameras
  40529. */
  40530. ArcRotateCamera.prototype._updateRigCameras = function () {
  40531. var camLeft = this._rigCameras[0];
  40532. var camRight = this._rigCameras[1];
  40533. camLeft.beta = camRight.beta = this.beta;
  40534. camLeft.radius = camRight.radius = this.radius;
  40535. switch (this.cameraRigMode) {
  40536. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  40537. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  40538. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  40539. case BABYLON.Camera.RIG_MODE_VR:
  40540. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  40541. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  40542. break;
  40543. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  40544. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  40545. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  40546. break;
  40547. }
  40548. _super.prototype._updateRigCameras.call(this);
  40549. };
  40550. ArcRotateCamera.prototype.dispose = function () {
  40551. this.inputs.clear();
  40552. _super.prototype.dispose.call(this);
  40553. };
  40554. ArcRotateCamera.prototype.getClassName = function () {
  40555. return "ArcRotateCamera";
  40556. };
  40557. __decorate([
  40558. BABYLON.serialize()
  40559. ], ArcRotateCamera.prototype, "alpha", void 0);
  40560. __decorate([
  40561. BABYLON.serialize()
  40562. ], ArcRotateCamera.prototype, "beta", void 0);
  40563. __decorate([
  40564. BABYLON.serialize()
  40565. ], ArcRotateCamera.prototype, "radius", void 0);
  40566. __decorate([
  40567. BABYLON.serializeAsVector3("target")
  40568. ], ArcRotateCamera.prototype, "_target", void 0);
  40569. __decorate([
  40570. BABYLON.serialize()
  40571. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  40572. __decorate([
  40573. BABYLON.serialize()
  40574. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  40575. __decorate([
  40576. BABYLON.serialize()
  40577. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  40578. __decorate([
  40579. BABYLON.serialize()
  40580. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  40581. __decorate([
  40582. BABYLON.serialize()
  40583. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  40584. __decorate([
  40585. BABYLON.serialize()
  40586. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  40587. __decorate([
  40588. BABYLON.serialize()
  40589. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  40590. __decorate([
  40591. BABYLON.serialize()
  40592. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  40593. __decorate([
  40594. BABYLON.serialize()
  40595. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  40596. __decorate([
  40597. BABYLON.serialize()
  40598. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  40599. __decorate([
  40600. BABYLON.serialize()
  40601. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  40602. __decorate([
  40603. BABYLON.serialize()
  40604. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  40605. __decorate([
  40606. BABYLON.serialize()
  40607. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  40608. __decorate([
  40609. BABYLON.serializeAsVector3()
  40610. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  40611. __decorate([
  40612. BABYLON.serialize()
  40613. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  40614. __decorate([
  40615. BABYLON.serialize()
  40616. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  40617. __decorate([
  40618. BABYLON.serialize()
  40619. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  40620. return ArcRotateCamera;
  40621. }(BABYLON.TargetCamera));
  40622. BABYLON.ArcRotateCamera = ArcRotateCamera;
  40623. })(BABYLON || (BABYLON = {}));
  40624. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  40625. var BABYLON;
  40626. (function (BABYLON) {
  40627. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  40628. __extends(ArcRotateCameraInputsManager, _super);
  40629. function ArcRotateCameraInputsManager(camera) {
  40630. return _super.call(this, camera) || this;
  40631. }
  40632. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  40633. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  40634. return this;
  40635. };
  40636. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  40637. this.add(new BABYLON.ArcRotateCameraPointersInput());
  40638. return this;
  40639. };
  40640. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  40641. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  40642. return this;
  40643. };
  40644. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  40645. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  40646. return this;
  40647. };
  40648. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  40649. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  40650. return this;
  40651. };
  40652. return ArcRotateCameraInputsManager;
  40653. }(BABYLON.CameraInputsManager));
  40654. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  40655. })(BABYLON || (BABYLON = {}));
  40656. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  40657. var BABYLON;
  40658. (function (BABYLON) {
  40659. var HemisphericLight = /** @class */ (function (_super) {
  40660. __extends(HemisphericLight, _super);
  40661. /**
  40662. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  40663. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  40664. * The HemisphericLight can't cast shadows.
  40665. * Documentation : http://doc.babylonjs.com/tutorials/lights
  40666. */
  40667. function HemisphericLight(name, direction, scene) {
  40668. var _this = _super.call(this, name, scene) || this;
  40669. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  40670. _this.direction = direction || BABYLON.Vector3.Up();
  40671. return _this;
  40672. }
  40673. HemisphericLight.prototype._buildUniformLayout = function () {
  40674. this._uniformBuffer.addUniform("vLightData", 4);
  40675. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  40676. this._uniformBuffer.addUniform("vLightSpecular", 3);
  40677. this._uniformBuffer.addUniform("vLightGround", 3);
  40678. this._uniformBuffer.addUniform("shadowsInfo", 3);
  40679. this._uniformBuffer.addUniform("depthValues", 2);
  40680. this._uniformBuffer.create();
  40681. };
  40682. /**
  40683. * Returns the string "HemisphericLight".
  40684. */
  40685. HemisphericLight.prototype.getClassName = function () {
  40686. return "HemisphericLight";
  40687. };
  40688. /**
  40689. * Sets the HemisphericLight direction towards the passed target (Vector3).
  40690. * Returns the updated direction.
  40691. */
  40692. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  40693. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  40694. return this.direction;
  40695. };
  40696. HemisphericLight.prototype.getShadowGenerator = function () {
  40697. return null;
  40698. };
  40699. /**
  40700. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  40701. * Returns the HemisphericLight.
  40702. */
  40703. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  40704. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  40705. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  40706. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  40707. return this;
  40708. };
  40709. HemisphericLight.prototype._getWorldMatrix = function () {
  40710. if (!this._worldMatrix) {
  40711. this._worldMatrix = BABYLON.Matrix.Identity();
  40712. }
  40713. return this._worldMatrix;
  40714. };
  40715. /**
  40716. * Returns the integer 3.
  40717. */
  40718. HemisphericLight.prototype.getTypeID = function () {
  40719. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  40720. };
  40721. __decorate([
  40722. BABYLON.serializeAsColor3()
  40723. ], HemisphericLight.prototype, "groundColor", void 0);
  40724. __decorate([
  40725. BABYLON.serializeAsVector3()
  40726. ], HemisphericLight.prototype, "direction", void 0);
  40727. return HemisphericLight;
  40728. }(BABYLON.Light));
  40729. BABYLON.HemisphericLight = HemisphericLight;
  40730. })(BABYLON || (BABYLON = {}));
  40731. //# sourceMappingURL=babylon.hemisphericLight.js.map
  40732. var BABYLON;
  40733. (function (BABYLON) {
  40734. var ShadowLight = /** @class */ (function (_super) {
  40735. __extends(ShadowLight, _super);
  40736. function ShadowLight() {
  40737. var _this = _super !== null && _super.apply(this, arguments) || this;
  40738. _this._needProjectionMatrixCompute = true;
  40739. return _this;
  40740. }
  40741. Object.defineProperty(ShadowLight.prototype, "direction", {
  40742. get: function () {
  40743. return this._direction;
  40744. },
  40745. set: function (value) {
  40746. this._direction = value;
  40747. },
  40748. enumerable: true,
  40749. configurable: true
  40750. });
  40751. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  40752. get: function () {
  40753. return this._shadowMinZ;
  40754. },
  40755. set: function (value) {
  40756. this._shadowMinZ = value;
  40757. this.forceProjectionMatrixCompute();
  40758. },
  40759. enumerable: true,
  40760. configurable: true
  40761. });
  40762. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  40763. get: function () {
  40764. return this._shadowMaxZ;
  40765. },
  40766. set: function (value) {
  40767. this._shadowMaxZ = value;
  40768. this.forceProjectionMatrixCompute();
  40769. },
  40770. enumerable: true,
  40771. configurable: true
  40772. });
  40773. /**
  40774. * Computes the light transformed position/direction in case the light is parented. Returns true if parented, else false.
  40775. */
  40776. ShadowLight.prototype.computeTransformedInformation = function () {
  40777. if (this.parent && this.parent.getWorldMatrix) {
  40778. if (!this.transformedPosition) {
  40779. this.transformedPosition = BABYLON.Vector3.Zero();
  40780. }
  40781. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  40782. // In case the direction is present.
  40783. if (this.direction) {
  40784. if (!this.transformedDirection) {
  40785. this.transformedDirection = BABYLON.Vector3.Zero();
  40786. }
  40787. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  40788. }
  40789. return true;
  40790. }
  40791. return false;
  40792. };
  40793. /**
  40794. * Return the depth scale used for the shadow map.
  40795. */
  40796. ShadowLight.prototype.getDepthScale = function () {
  40797. return 50.0;
  40798. };
  40799. /**
  40800. * Returns the light direction (Vector3) for any passed face index.
  40801. */
  40802. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  40803. return this.transformedDirection ? this.transformedDirection : this.direction;
  40804. };
  40805. /**
  40806. * Returns the DirectionalLight absolute position in the World.
  40807. */
  40808. ShadowLight.prototype.getAbsolutePosition = function () {
  40809. return this.transformedPosition ? this.transformedPosition : this.position;
  40810. };
  40811. /**
  40812. * Sets the DirectionalLight direction toward the passed target (Vector3).
  40813. * Returns the updated DirectionalLight direction (Vector3).
  40814. */
  40815. ShadowLight.prototype.setDirectionToTarget = function (target) {
  40816. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  40817. return this.direction;
  40818. };
  40819. /**
  40820. * Returns the light rotation (Vector3).
  40821. */
  40822. ShadowLight.prototype.getRotation = function () {
  40823. this.direction.normalize();
  40824. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  40825. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  40826. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  40827. };
  40828. /**
  40829. * Boolean : false by default.
  40830. */
  40831. ShadowLight.prototype.needCube = function () {
  40832. return false;
  40833. };
  40834. /**
  40835. * Specifies wether or not the projection matrix should be recomputed this frame.
  40836. */
  40837. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  40838. return this._needProjectionMatrixCompute;
  40839. };
  40840. /**
  40841. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  40842. */
  40843. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  40844. this._needProjectionMatrixCompute = true;
  40845. };
  40846. /**
  40847. * Get the world matrix of the sahdow lights.
  40848. */
  40849. ShadowLight.prototype._getWorldMatrix = function () {
  40850. if (!this._worldMatrix) {
  40851. this._worldMatrix = BABYLON.Matrix.Identity();
  40852. }
  40853. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  40854. return this._worldMatrix;
  40855. };
  40856. /**
  40857. * Gets the minZ used for shadow according to both the scene and the light.
  40858. * @param activeCamera
  40859. */
  40860. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  40861. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  40862. };
  40863. /**
  40864. * Gets the maxZ used for shadow according to both the scene and the light.
  40865. * @param activeCamera
  40866. */
  40867. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  40868. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  40869. };
  40870. /**
  40871. * Sets the projection matrix according to the type of light and custom projection matrix definition.
  40872. * Returns the light.
  40873. */
  40874. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  40875. if (this.customProjectionMatrixBuilder) {
  40876. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  40877. }
  40878. else {
  40879. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  40880. }
  40881. return this;
  40882. };
  40883. __decorate([
  40884. BABYLON.serializeAsVector3()
  40885. ], ShadowLight.prototype, "position", void 0);
  40886. __decorate([
  40887. BABYLON.serializeAsVector3()
  40888. ], ShadowLight.prototype, "direction", null);
  40889. __decorate([
  40890. BABYLON.serialize()
  40891. ], ShadowLight.prototype, "shadowMinZ", null);
  40892. __decorate([
  40893. BABYLON.serialize()
  40894. ], ShadowLight.prototype, "shadowMaxZ", null);
  40895. return ShadowLight;
  40896. }(BABYLON.Light));
  40897. BABYLON.ShadowLight = ShadowLight;
  40898. })(BABYLON || (BABYLON = {}));
  40899. //# sourceMappingURL=babylon.shadowLight.js.map
  40900. var BABYLON;
  40901. (function (BABYLON) {
  40902. var PointLight = /** @class */ (function (_super) {
  40903. __extends(PointLight, _super);
  40904. /**
  40905. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  40906. * A PointLight emits the light in every direction.
  40907. * It can cast shadows.
  40908. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  40909. * ```javascript
  40910. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  40911. * ```
  40912. * Documentation : http://doc.babylonjs.com/tutorials/lights
  40913. */
  40914. function PointLight(name, position, scene) {
  40915. var _this = _super.call(this, name, scene) || this;
  40916. _this._shadowAngle = Math.PI / 2;
  40917. _this.position = position;
  40918. return _this;
  40919. }
  40920. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  40921. /**
  40922. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  40923. * This specifies what angle the shadow will use to be created.
  40924. *
  40925. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  40926. */
  40927. get: function () {
  40928. return this._shadowAngle;
  40929. },
  40930. /**
  40931. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  40932. * This specifies what angle the shadow will use to be created.
  40933. *
  40934. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  40935. */
  40936. set: function (value) {
  40937. this._shadowAngle = value;
  40938. this.forceProjectionMatrixCompute();
  40939. },
  40940. enumerable: true,
  40941. configurable: true
  40942. });
  40943. Object.defineProperty(PointLight.prototype, "direction", {
  40944. get: function () {
  40945. return this._direction;
  40946. },
  40947. /**
  40948. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  40949. */
  40950. set: function (value) {
  40951. var previousNeedCube = this.needCube();
  40952. this._direction = value;
  40953. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  40954. this._shadowGenerator.recreateShadowMap();
  40955. }
  40956. },
  40957. enumerable: true,
  40958. configurable: true
  40959. });
  40960. /**
  40961. * Returns the string "PointLight"
  40962. */
  40963. PointLight.prototype.getClassName = function () {
  40964. return "PointLight";
  40965. };
  40966. /**
  40967. * Returns the integer 0.
  40968. */
  40969. PointLight.prototype.getTypeID = function () {
  40970. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  40971. };
  40972. /**
  40973. * Specifies wether or not the shadowmap should be a cube texture.
  40974. */
  40975. PointLight.prototype.needCube = function () {
  40976. return !this.direction;
  40977. };
  40978. /**
  40979. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  40980. */
  40981. PointLight.prototype.getShadowDirection = function (faceIndex) {
  40982. if (this.direction) {
  40983. return _super.prototype.getShadowDirection.call(this, faceIndex);
  40984. }
  40985. else {
  40986. switch (faceIndex) {
  40987. case 0:
  40988. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  40989. case 1:
  40990. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  40991. case 2:
  40992. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  40993. case 3:
  40994. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  40995. case 4:
  40996. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  40997. case 5:
  40998. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  40999. }
  41000. }
  41001. return BABYLON.Vector3.Zero();
  41002. };
  41003. /**
  41004. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  41005. * - fov = PI / 2
  41006. * - aspect ratio : 1.0
  41007. * - z-near and far equal to the active camera minZ and maxZ.
  41008. * Returns the PointLight.
  41009. */
  41010. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  41011. var activeCamera = this.getScene().activeCamera;
  41012. if (!activeCamera) {
  41013. return;
  41014. }
  41015. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  41016. };
  41017. PointLight.prototype._buildUniformLayout = function () {
  41018. this._uniformBuffer.addUniform("vLightData", 4);
  41019. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  41020. this._uniformBuffer.addUniform("vLightSpecular", 3);
  41021. this._uniformBuffer.addUniform("shadowsInfo", 3);
  41022. this._uniformBuffer.addUniform("depthValues", 2);
  41023. this._uniformBuffer.create();
  41024. };
  41025. /**
  41026. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  41027. * Returns the PointLight.
  41028. */
  41029. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  41030. if (this.computeTransformedInformation()) {
  41031. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  41032. return this;
  41033. }
  41034. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  41035. return this;
  41036. };
  41037. __decorate([
  41038. BABYLON.serialize()
  41039. ], PointLight.prototype, "shadowAngle", null);
  41040. return PointLight;
  41041. }(BABYLON.ShadowLight));
  41042. BABYLON.PointLight = PointLight;
  41043. })(BABYLON || (BABYLON = {}));
  41044. //# sourceMappingURL=babylon.pointLight.js.map
  41045. var BABYLON;
  41046. (function (BABYLON) {
  41047. var DirectionalLight = /** @class */ (function (_super) {
  41048. __extends(DirectionalLight, _super);
  41049. /**
  41050. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  41051. * The directional light is emitted from everywhere in the given direction.
  41052. * It can cast shawdows.
  41053. * Documentation : http://doc.babylonjs.com/tutorials/lights
  41054. */
  41055. function DirectionalLight(name, direction, scene) {
  41056. var _this = _super.call(this, name, scene) || this;
  41057. _this._shadowFrustumSize = 0;
  41058. _this._shadowOrthoScale = 0.5;
  41059. _this.autoUpdateExtends = true;
  41060. // Cache
  41061. _this._orthoLeft = Number.MAX_VALUE;
  41062. _this._orthoRight = Number.MIN_VALUE;
  41063. _this._orthoTop = Number.MIN_VALUE;
  41064. _this._orthoBottom = Number.MAX_VALUE;
  41065. _this.position = direction.scale(-1.0);
  41066. _this.direction = direction;
  41067. return _this;
  41068. }
  41069. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  41070. /**
  41071. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  41072. */
  41073. get: function () {
  41074. return this._shadowFrustumSize;
  41075. },
  41076. /**
  41077. * Specifies a fix frustum size for the shadow generation.
  41078. */
  41079. set: function (value) {
  41080. this._shadowFrustumSize = value;
  41081. this.forceProjectionMatrixCompute();
  41082. },
  41083. enumerable: true,
  41084. configurable: true
  41085. });
  41086. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  41087. get: function () {
  41088. return this._shadowOrthoScale;
  41089. },
  41090. set: function (value) {
  41091. this._shadowOrthoScale = value;
  41092. this.forceProjectionMatrixCompute();
  41093. },
  41094. enumerable: true,
  41095. configurable: true
  41096. });
  41097. /**
  41098. * Returns the string "DirectionalLight".
  41099. */
  41100. DirectionalLight.prototype.getClassName = function () {
  41101. return "DirectionalLight";
  41102. };
  41103. /**
  41104. * Returns the integer 1.
  41105. */
  41106. DirectionalLight.prototype.getTypeID = function () {
  41107. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  41108. };
  41109. /**
  41110. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  41111. * Returns the DirectionalLight Shadow projection matrix.
  41112. */
  41113. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  41114. if (this.shadowFrustumSize > 0) {
  41115. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  41116. }
  41117. else {
  41118. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  41119. }
  41120. };
  41121. /**
  41122. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  41123. * Returns the DirectionalLight Shadow projection matrix.
  41124. */
  41125. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  41126. var activeCamera = this.getScene().activeCamera;
  41127. if (!activeCamera) {
  41128. return;
  41129. }
  41130. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  41131. };
  41132. /**
  41133. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  41134. * Returns the DirectionalLight Shadow projection matrix.
  41135. */
  41136. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  41137. var activeCamera = this.getScene().activeCamera;
  41138. if (!activeCamera) {
  41139. return;
  41140. }
  41141. // Check extends
  41142. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  41143. var tempVector3 = BABYLON.Vector3.Zero();
  41144. this._orthoLeft = Number.MAX_VALUE;
  41145. this._orthoRight = Number.MIN_VALUE;
  41146. this._orthoTop = Number.MIN_VALUE;
  41147. this._orthoBottom = Number.MAX_VALUE;
  41148. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  41149. var mesh = renderList[meshIndex];
  41150. if (!mesh) {
  41151. continue;
  41152. }
  41153. var boundingInfo = mesh.getBoundingInfo();
  41154. var boundingBox = boundingInfo.boundingBox;
  41155. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  41156. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  41157. if (tempVector3.x < this._orthoLeft)
  41158. this._orthoLeft = tempVector3.x;
  41159. if (tempVector3.y < this._orthoBottom)
  41160. this._orthoBottom = tempVector3.y;
  41161. if (tempVector3.x > this._orthoRight)
  41162. this._orthoRight = tempVector3.x;
  41163. if (tempVector3.y > this._orthoTop)
  41164. this._orthoTop = tempVector3.y;
  41165. }
  41166. }
  41167. }
  41168. var xOffset = this._orthoRight - this._orthoLeft;
  41169. var yOffset = this._orthoTop - this._orthoBottom;
  41170. 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);
  41171. };
  41172. DirectionalLight.prototype._buildUniformLayout = function () {
  41173. this._uniformBuffer.addUniform("vLightData", 4);
  41174. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  41175. this._uniformBuffer.addUniform("vLightSpecular", 3);
  41176. this._uniformBuffer.addUniform("shadowsInfo", 3);
  41177. this._uniformBuffer.addUniform("depthValues", 2);
  41178. this._uniformBuffer.create();
  41179. };
  41180. /**
  41181. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  41182. * Returns the DirectionalLight.
  41183. */
  41184. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  41185. if (this.computeTransformedInformation()) {
  41186. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  41187. return this;
  41188. }
  41189. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  41190. return this;
  41191. };
  41192. /**
  41193. * Gets the minZ used for shadow according to both the scene and the light.
  41194. *
  41195. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  41196. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  41197. * @param activeCamera
  41198. */
  41199. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  41200. return 1;
  41201. };
  41202. /**
  41203. * Gets the maxZ used for shadow according to both the scene and the light.
  41204. *
  41205. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  41206. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  41207. * @param activeCamera
  41208. */
  41209. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  41210. return 1;
  41211. };
  41212. __decorate([
  41213. BABYLON.serialize()
  41214. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  41215. __decorate([
  41216. BABYLON.serialize()
  41217. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  41218. __decorate([
  41219. BABYLON.serialize()
  41220. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  41221. return DirectionalLight;
  41222. }(BABYLON.ShadowLight));
  41223. BABYLON.DirectionalLight = DirectionalLight;
  41224. })(BABYLON || (BABYLON = {}));
  41225. //# sourceMappingURL=babylon.directionalLight.js.map
  41226. var BABYLON;
  41227. (function (BABYLON) {
  41228. var SpotLight = /** @class */ (function (_super) {
  41229. __extends(SpotLight, _super);
  41230. /**
  41231. * Creates a SpotLight object in the scene with the passed parameters :
  41232. * - `position` (Vector3) is the initial SpotLight position,
  41233. * - `direction` (Vector3) is the initial SpotLight direction,
  41234. * - `angle` (float, in radians) is the spot light cone angle,
  41235. * - `exponent` (float) is the light decay speed with the distance from the emission spot.
  41236. * A spot light is a simply light oriented cone.
  41237. * It can cast shadows.
  41238. * Documentation : http://doc.babylonjs.com/tutorials/lights
  41239. */
  41240. function SpotLight(name, position, direction, angle, exponent, scene) {
  41241. var _this = _super.call(this, name, scene) || this;
  41242. _this.position = position;
  41243. _this.direction = direction;
  41244. _this.angle = angle;
  41245. _this.exponent = exponent;
  41246. return _this;
  41247. }
  41248. Object.defineProperty(SpotLight.prototype, "angle", {
  41249. get: function () {
  41250. return this._angle;
  41251. },
  41252. set: function (value) {
  41253. this._angle = value;
  41254. this.forceProjectionMatrixCompute();
  41255. },
  41256. enumerable: true,
  41257. configurable: true
  41258. });
  41259. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  41260. get: function () {
  41261. return this._shadowAngleScale;
  41262. },
  41263. /**
  41264. * Allows scaling the angle of the light for shadow generation only.
  41265. */
  41266. set: function (value) {
  41267. this._shadowAngleScale = value;
  41268. this.forceProjectionMatrixCompute();
  41269. },
  41270. enumerable: true,
  41271. configurable: true
  41272. });
  41273. /**
  41274. * Returns the string "SpotLight".
  41275. */
  41276. SpotLight.prototype.getClassName = function () {
  41277. return "SpotLight";
  41278. };
  41279. /**
  41280. * Returns the integer 2.
  41281. */
  41282. SpotLight.prototype.getTypeID = function () {
  41283. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  41284. };
  41285. /**
  41286. * 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.
  41287. * Returns the SpotLight.
  41288. */
  41289. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  41290. var activeCamera = this.getScene().activeCamera;
  41291. if (!activeCamera) {
  41292. return;
  41293. }
  41294. this._shadowAngleScale = this._shadowAngleScale || 1;
  41295. var angle = this._shadowAngleScale * this._angle;
  41296. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  41297. };
  41298. SpotLight.prototype._buildUniformLayout = function () {
  41299. this._uniformBuffer.addUniform("vLightData", 4);
  41300. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  41301. this._uniformBuffer.addUniform("vLightSpecular", 3);
  41302. this._uniformBuffer.addUniform("vLightDirection", 3);
  41303. this._uniformBuffer.addUniform("shadowsInfo", 3);
  41304. this._uniformBuffer.addUniform("depthValues", 2);
  41305. this._uniformBuffer.create();
  41306. };
  41307. /**
  41308. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  41309. * Return the SpotLight.
  41310. */
  41311. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  41312. var normalizeDirection;
  41313. if (this.computeTransformedInformation()) {
  41314. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  41315. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  41316. }
  41317. else {
  41318. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  41319. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  41320. }
  41321. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  41322. return this;
  41323. };
  41324. __decorate([
  41325. BABYLON.serialize()
  41326. ], SpotLight.prototype, "angle", null);
  41327. __decorate([
  41328. BABYLON.serialize()
  41329. /**
  41330. * Allows scaling the angle of the light for shadow generation only.
  41331. */
  41332. ], SpotLight.prototype, "shadowAngleScale", null);
  41333. __decorate([
  41334. BABYLON.serialize()
  41335. ], SpotLight.prototype, "exponent", void 0);
  41336. return SpotLight;
  41337. }(BABYLON.ShadowLight));
  41338. BABYLON.SpotLight = SpotLight;
  41339. })(BABYLON || (BABYLON = {}));
  41340. //# sourceMappingURL=babylon.spotLight.js.map
  41341. var BABYLON;
  41342. (function (BABYLON) {
  41343. var AnimationRange = /** @class */ (function () {
  41344. function AnimationRange(name, from, to) {
  41345. this.name = name;
  41346. this.from = from;
  41347. this.to = to;
  41348. }
  41349. AnimationRange.prototype.clone = function () {
  41350. return new AnimationRange(this.name, this.from, this.to);
  41351. };
  41352. return AnimationRange;
  41353. }());
  41354. BABYLON.AnimationRange = AnimationRange;
  41355. /**
  41356. * Composed of a frame, and an action function
  41357. */
  41358. var AnimationEvent = /** @class */ (function () {
  41359. function AnimationEvent(frame, action, onlyOnce) {
  41360. this.frame = frame;
  41361. this.action = action;
  41362. this.onlyOnce = onlyOnce;
  41363. this.isDone = false;
  41364. }
  41365. return AnimationEvent;
  41366. }());
  41367. BABYLON.AnimationEvent = AnimationEvent;
  41368. var PathCursor = /** @class */ (function () {
  41369. function PathCursor(path) {
  41370. this.path = path;
  41371. this._onchange = new Array();
  41372. this.value = 0;
  41373. this.animations = new Array();
  41374. }
  41375. PathCursor.prototype.getPoint = function () {
  41376. var point = this.path.getPointAtLengthPosition(this.value);
  41377. return new BABYLON.Vector3(point.x, 0, point.y);
  41378. };
  41379. PathCursor.prototype.moveAhead = function (step) {
  41380. if (step === void 0) { step = 0.002; }
  41381. this.move(step);
  41382. return this;
  41383. };
  41384. PathCursor.prototype.moveBack = function (step) {
  41385. if (step === void 0) { step = 0.002; }
  41386. this.move(-step);
  41387. return this;
  41388. };
  41389. PathCursor.prototype.move = function (step) {
  41390. if (Math.abs(step) > 1) {
  41391. throw "step size should be less than 1.";
  41392. }
  41393. this.value += step;
  41394. this.ensureLimits();
  41395. this.raiseOnChange();
  41396. return this;
  41397. };
  41398. PathCursor.prototype.ensureLimits = function () {
  41399. while (this.value > 1) {
  41400. this.value -= 1;
  41401. }
  41402. while (this.value < 0) {
  41403. this.value += 1;
  41404. }
  41405. return this;
  41406. };
  41407. // used by animation engine
  41408. PathCursor.prototype.raiseOnChange = function () {
  41409. var _this = this;
  41410. this._onchange.forEach(function (f) { return f(_this); });
  41411. return this;
  41412. };
  41413. PathCursor.prototype.onchange = function (f) {
  41414. this._onchange.push(f);
  41415. return this;
  41416. };
  41417. return PathCursor;
  41418. }());
  41419. BABYLON.PathCursor = PathCursor;
  41420. var Animation = /** @class */ (function () {
  41421. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  41422. this.name = name;
  41423. this.targetProperty = targetProperty;
  41424. this.framePerSecond = framePerSecond;
  41425. this.dataType = dataType;
  41426. this.loopMode = loopMode;
  41427. this.enableBlending = enableBlending;
  41428. this._runtimeAnimations = new Array();
  41429. // The set of event that will be linked to this animation
  41430. this._events = new Array();
  41431. this.blendingSpeed = 0.01;
  41432. this._ranges = {};
  41433. this.targetPropertyPath = targetProperty.split(".");
  41434. this.dataType = dataType;
  41435. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  41436. }
  41437. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  41438. var dataType = undefined;
  41439. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  41440. dataType = Animation.ANIMATIONTYPE_FLOAT;
  41441. }
  41442. else if (from instanceof BABYLON.Quaternion) {
  41443. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  41444. }
  41445. else if (from instanceof BABYLON.Vector3) {
  41446. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  41447. }
  41448. else if (from instanceof BABYLON.Vector2) {
  41449. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  41450. }
  41451. else if (from instanceof BABYLON.Color3) {
  41452. dataType = Animation.ANIMATIONTYPE_COLOR3;
  41453. }
  41454. else if (from instanceof BABYLON.Size) {
  41455. dataType = Animation.ANIMATIONTYPE_SIZE;
  41456. }
  41457. if (dataType == undefined) {
  41458. return null;
  41459. }
  41460. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  41461. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  41462. animation.setKeys(keys);
  41463. if (easingFunction !== undefined) {
  41464. animation.setEasingFunction(easingFunction);
  41465. }
  41466. return animation;
  41467. };
  41468. /**
  41469. * Sets up an animation.
  41470. * @param property the property to animate
  41471. * @param animationType the animation type to apply
  41472. * @param easingFunction the easing function used in the animation
  41473. * @returns The created animation
  41474. */
  41475. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  41476. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  41477. animation.setEasingFunction(easingFunction);
  41478. return animation;
  41479. };
  41480. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  41481. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  41482. if (!animation) {
  41483. return null;
  41484. }
  41485. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  41486. };
  41487. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  41488. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  41489. if (!animation) {
  41490. return null;
  41491. }
  41492. node.animations.push(animation);
  41493. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  41494. };
  41495. /**
  41496. * Transition property of the Camera to the target Value.
  41497. * @param property The property to transition
  41498. * @param targetValue The target Value of the property
  41499. * @param host The object where the property to animate belongs
  41500. * @param scene Scene used to run the animation
  41501. * @param frameRate Framerate (in frame/s) to use
  41502. * @param transition The transition type we want to use
  41503. * @param duration The duration of the animation, in milliseconds
  41504. * @param onAnimationEnd Call back trigger at the end of the animation.
  41505. */
  41506. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  41507. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  41508. if (duration <= 0) {
  41509. host[property] = targetValue;
  41510. if (onAnimationEnd) {
  41511. onAnimationEnd();
  41512. }
  41513. return null;
  41514. }
  41515. var endFrame = frameRate * (duration / 1000);
  41516. transition.setKeys([{
  41517. frame: 0,
  41518. value: host[property].clone ? host[property].clone() : host[property]
  41519. },
  41520. {
  41521. frame: endFrame,
  41522. value: targetValue
  41523. }]);
  41524. if (!host.animations) {
  41525. host.animations = [];
  41526. }
  41527. host.animations.push(transition);
  41528. var animation = scene.beginAnimation(host, 0, endFrame, false);
  41529. animation.onAnimationEnd = onAnimationEnd;
  41530. return animation;
  41531. };
  41532. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  41533. /**
  41534. * Return the array of runtime animations currently using this animation
  41535. */
  41536. get: function () {
  41537. return this._runtimeAnimations;
  41538. },
  41539. enumerable: true,
  41540. configurable: true
  41541. });
  41542. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  41543. get: function () {
  41544. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  41545. var runtimeAnimation = _a[_i];
  41546. if (!runtimeAnimation.isStopped) {
  41547. return true;
  41548. }
  41549. }
  41550. return false;
  41551. },
  41552. enumerable: true,
  41553. configurable: true
  41554. });
  41555. // Methods
  41556. /**
  41557. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  41558. */
  41559. Animation.prototype.toString = function (fullDetails) {
  41560. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  41561. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  41562. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  41563. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  41564. if (fullDetails) {
  41565. ret += ", Ranges: {";
  41566. var first = true;
  41567. for (var name in this._ranges) {
  41568. if (first) {
  41569. ret += ", ";
  41570. first = false;
  41571. }
  41572. ret += name;
  41573. }
  41574. ret += "}";
  41575. }
  41576. return ret;
  41577. };
  41578. /**
  41579. * Add an event to this animation.
  41580. */
  41581. Animation.prototype.addEvent = function (event) {
  41582. this._events.push(event);
  41583. };
  41584. /**
  41585. * Remove all events found at the given frame
  41586. * @param frame
  41587. */
  41588. Animation.prototype.removeEvents = function (frame) {
  41589. for (var index = 0; index < this._events.length; index++) {
  41590. if (this._events[index].frame === frame) {
  41591. this._events.splice(index, 1);
  41592. index--;
  41593. }
  41594. }
  41595. };
  41596. Animation.prototype.getEvents = function () {
  41597. return this._events;
  41598. };
  41599. Animation.prototype.createRange = function (name, from, to) {
  41600. // check name not already in use; could happen for bones after serialized
  41601. if (!this._ranges[name]) {
  41602. this._ranges[name] = new AnimationRange(name, from, to);
  41603. }
  41604. };
  41605. Animation.prototype.deleteRange = function (name, deleteFrames) {
  41606. if (deleteFrames === void 0) { deleteFrames = true; }
  41607. var range = this._ranges[name];
  41608. if (!range) {
  41609. return;
  41610. }
  41611. if (deleteFrames) {
  41612. var from = range.from;
  41613. var to = range.to;
  41614. // this loop MUST go high to low for multiple splices to work
  41615. for (var key = this._keys.length - 1; key >= 0; key--) {
  41616. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  41617. this._keys.splice(key, 1);
  41618. }
  41619. }
  41620. }
  41621. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  41622. };
  41623. Animation.prototype.getRange = function (name) {
  41624. return this._ranges[name];
  41625. };
  41626. Animation.prototype.getKeys = function () {
  41627. return this._keys;
  41628. };
  41629. Animation.prototype.getHighestFrame = function () {
  41630. var ret = 0;
  41631. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  41632. if (ret < this._keys[key].frame) {
  41633. ret = this._keys[key].frame;
  41634. }
  41635. }
  41636. return ret;
  41637. };
  41638. Animation.prototype.getEasingFunction = function () {
  41639. return this._easingFunction;
  41640. };
  41641. Animation.prototype.setEasingFunction = function (easingFunction) {
  41642. this._easingFunction = easingFunction;
  41643. };
  41644. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  41645. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  41646. };
  41647. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  41648. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  41649. };
  41650. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  41651. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  41652. };
  41653. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  41654. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  41655. };
  41656. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  41657. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  41658. };
  41659. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  41660. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  41661. };
  41662. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  41663. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  41664. };
  41665. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  41666. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  41667. };
  41668. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  41669. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  41670. };
  41671. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  41672. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  41673. };
  41674. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  41675. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  41676. };
  41677. Animation.prototype.clone = function () {
  41678. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  41679. clone.enableBlending = this.enableBlending;
  41680. clone.blendingSpeed = this.blendingSpeed;
  41681. if (this._keys) {
  41682. clone.setKeys(this._keys);
  41683. }
  41684. if (this._ranges) {
  41685. clone._ranges = {};
  41686. for (var name in this._ranges) {
  41687. var range = this._ranges[name];
  41688. if (!range) {
  41689. continue;
  41690. }
  41691. clone._ranges[name] = range.clone();
  41692. }
  41693. }
  41694. return clone;
  41695. };
  41696. Animation.prototype.setKeys = function (values) {
  41697. this._keys = values.slice(0);
  41698. };
  41699. Animation.prototype.serialize = function () {
  41700. var serializationObject = {};
  41701. serializationObject.name = this.name;
  41702. serializationObject.property = this.targetProperty;
  41703. serializationObject.framePerSecond = this.framePerSecond;
  41704. serializationObject.dataType = this.dataType;
  41705. serializationObject.loopBehavior = this.loopMode;
  41706. serializationObject.enableBlending = this.enableBlending;
  41707. serializationObject.blendingSpeed = this.blendingSpeed;
  41708. var dataType = this.dataType;
  41709. serializationObject.keys = [];
  41710. var keys = this.getKeys();
  41711. for (var index = 0; index < keys.length; index++) {
  41712. var animationKey = keys[index];
  41713. var key = {};
  41714. key.frame = animationKey.frame;
  41715. switch (dataType) {
  41716. case Animation.ANIMATIONTYPE_FLOAT:
  41717. key.values = [animationKey.value];
  41718. break;
  41719. case Animation.ANIMATIONTYPE_QUATERNION:
  41720. case Animation.ANIMATIONTYPE_MATRIX:
  41721. case Animation.ANIMATIONTYPE_VECTOR3:
  41722. case Animation.ANIMATIONTYPE_COLOR3:
  41723. key.values = animationKey.value.asArray();
  41724. break;
  41725. }
  41726. serializationObject.keys.push(key);
  41727. }
  41728. serializationObject.ranges = [];
  41729. for (var name in this._ranges) {
  41730. var source = this._ranges[name];
  41731. if (!source) {
  41732. continue;
  41733. }
  41734. var range = {};
  41735. range.name = name;
  41736. range.from = source.from;
  41737. range.to = source.to;
  41738. serializationObject.ranges.push(range);
  41739. }
  41740. return serializationObject;
  41741. };
  41742. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  41743. get: function () {
  41744. return Animation._ANIMATIONTYPE_FLOAT;
  41745. },
  41746. enumerable: true,
  41747. configurable: true
  41748. });
  41749. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  41750. get: function () {
  41751. return Animation._ANIMATIONTYPE_VECTOR3;
  41752. },
  41753. enumerable: true,
  41754. configurable: true
  41755. });
  41756. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  41757. get: function () {
  41758. return Animation._ANIMATIONTYPE_VECTOR2;
  41759. },
  41760. enumerable: true,
  41761. configurable: true
  41762. });
  41763. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  41764. get: function () {
  41765. return Animation._ANIMATIONTYPE_SIZE;
  41766. },
  41767. enumerable: true,
  41768. configurable: true
  41769. });
  41770. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  41771. get: function () {
  41772. return Animation._ANIMATIONTYPE_QUATERNION;
  41773. },
  41774. enumerable: true,
  41775. configurable: true
  41776. });
  41777. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  41778. get: function () {
  41779. return Animation._ANIMATIONTYPE_MATRIX;
  41780. },
  41781. enumerable: true,
  41782. configurable: true
  41783. });
  41784. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  41785. get: function () {
  41786. return Animation._ANIMATIONTYPE_COLOR3;
  41787. },
  41788. enumerable: true,
  41789. configurable: true
  41790. });
  41791. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  41792. get: function () {
  41793. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  41794. },
  41795. enumerable: true,
  41796. configurable: true
  41797. });
  41798. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  41799. get: function () {
  41800. return Animation._ANIMATIONLOOPMODE_CYCLE;
  41801. },
  41802. enumerable: true,
  41803. configurable: true
  41804. });
  41805. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  41806. get: function () {
  41807. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  41808. },
  41809. enumerable: true,
  41810. configurable: true
  41811. });
  41812. Animation.Parse = function (parsedAnimation) {
  41813. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  41814. var dataType = parsedAnimation.dataType;
  41815. var keys = [];
  41816. var data;
  41817. var index;
  41818. if (parsedAnimation.enableBlending) {
  41819. animation.enableBlending = parsedAnimation.enableBlending;
  41820. }
  41821. if (parsedAnimation.blendingSpeed) {
  41822. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  41823. }
  41824. for (index = 0; index < parsedAnimation.keys.length; index++) {
  41825. var key = parsedAnimation.keys[index];
  41826. var inTangent;
  41827. var outTangent;
  41828. switch (dataType) {
  41829. case Animation.ANIMATIONTYPE_FLOAT:
  41830. data = key.values[0];
  41831. if (key.values.length >= 1) {
  41832. inTangent = key.values[1];
  41833. }
  41834. if (key.values.length >= 2) {
  41835. outTangent = key.values[2];
  41836. }
  41837. break;
  41838. case Animation.ANIMATIONTYPE_QUATERNION:
  41839. data = BABYLON.Quaternion.FromArray(key.values);
  41840. if (key.values.length >= 8) {
  41841. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  41842. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  41843. inTangent = _inTangent;
  41844. }
  41845. }
  41846. if (key.values.length >= 12) {
  41847. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  41848. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  41849. outTangent = _outTangent;
  41850. }
  41851. }
  41852. break;
  41853. case Animation.ANIMATIONTYPE_MATRIX:
  41854. data = BABYLON.Matrix.FromArray(key.values);
  41855. break;
  41856. case Animation.ANIMATIONTYPE_COLOR3:
  41857. data = BABYLON.Color3.FromArray(key.values);
  41858. break;
  41859. case Animation.ANIMATIONTYPE_VECTOR3:
  41860. default:
  41861. data = BABYLON.Vector3.FromArray(key.values);
  41862. break;
  41863. }
  41864. var keyData = {};
  41865. keyData.frame = key.frame;
  41866. keyData.value = data;
  41867. if (inTangent != undefined) {
  41868. keyData.inTangent = inTangent;
  41869. }
  41870. if (outTangent != undefined) {
  41871. keyData.outTangent = outTangent;
  41872. }
  41873. keys.push(keyData);
  41874. }
  41875. animation.setKeys(keys);
  41876. if (parsedAnimation.ranges) {
  41877. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  41878. data = parsedAnimation.ranges[index];
  41879. animation.createRange(data.name, data.from, data.to);
  41880. }
  41881. }
  41882. return animation;
  41883. };
  41884. Animation.AppendSerializedAnimations = function (source, destination) {
  41885. if (source.animations) {
  41886. destination.animations = [];
  41887. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  41888. var animation = source.animations[animationIndex];
  41889. destination.animations.push(animation.serialize());
  41890. }
  41891. }
  41892. };
  41893. Animation.AllowMatricesInterpolation = false;
  41894. // Statics
  41895. Animation._ANIMATIONTYPE_FLOAT = 0;
  41896. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  41897. Animation._ANIMATIONTYPE_QUATERNION = 2;
  41898. Animation._ANIMATIONTYPE_MATRIX = 3;
  41899. Animation._ANIMATIONTYPE_COLOR3 = 4;
  41900. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  41901. Animation._ANIMATIONTYPE_SIZE = 6;
  41902. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  41903. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  41904. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  41905. return Animation;
  41906. }());
  41907. BABYLON.Animation = Animation;
  41908. })(BABYLON || (BABYLON = {}));
  41909. //# sourceMappingURL=babylon.animation.js.map
  41910. var BABYLON;
  41911. (function (BABYLON) {
  41912. /**
  41913. * This class defines the direct association between an animation and a target
  41914. */
  41915. var TargetedAnimation = /** @class */ (function () {
  41916. function TargetedAnimation() {
  41917. }
  41918. return TargetedAnimation;
  41919. }());
  41920. BABYLON.TargetedAnimation = TargetedAnimation;
  41921. /**
  41922. * Use this class to create coordinated animations on multiple targets
  41923. */
  41924. var AnimationGroup = /** @class */ (function () {
  41925. function AnimationGroup(name, scene) {
  41926. if (scene === void 0) { scene = null; }
  41927. this.name = name;
  41928. this._targetedAnimations = new Array();
  41929. this._animatables = new Array();
  41930. this._from = Number.MAX_VALUE;
  41931. this._to = Number.MIN_VALUE;
  41932. this._speedRatio = 1;
  41933. this.onAnimationEndObservable = new BABYLON.Observable();
  41934. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  41935. this._scene.animationGroups.push(this);
  41936. }
  41937. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  41938. /**
  41939. * Define if the animations are started
  41940. */
  41941. get: function () {
  41942. return this._isStarted;
  41943. },
  41944. enumerable: true,
  41945. configurable: true
  41946. });
  41947. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  41948. /**
  41949. * Gets or sets the speed ratio to use for all animations
  41950. */
  41951. get: function () {
  41952. return this._speedRatio;
  41953. },
  41954. /**
  41955. * Gets or sets the speed ratio to use for all animations
  41956. */
  41957. set: function (value) {
  41958. if (this._speedRatio === value) {
  41959. return;
  41960. }
  41961. for (var index = 0; index < this._animatables.length; index++) {
  41962. var animatable = this._animatables[index];
  41963. animatable.speedRatio = this._speedRatio;
  41964. }
  41965. },
  41966. enumerable: true,
  41967. configurable: true
  41968. });
  41969. /**
  41970. * Add an animation (with its target) in the group
  41971. * @param animation defines the animation we want to add
  41972. * @param target defines the target of the animation
  41973. * @returns the {BABYLON.TargetedAnimation} object
  41974. */
  41975. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  41976. var targetedAnimation = {
  41977. animation: animation,
  41978. target: target
  41979. };
  41980. var keys = animation.getKeys();
  41981. if (this._from > keys[0].frame) {
  41982. this._from = keys[0].frame;
  41983. }
  41984. if (this._to < keys[keys.length - 1].frame) {
  41985. this._to = keys[keys.length - 1].frame;
  41986. }
  41987. this._targetedAnimations.push(targetedAnimation);
  41988. return targetedAnimation;
  41989. };
  41990. /**
  41991. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  41992. * It can add constant keys at begin or end
  41993. * @param beginFrame defines the new begin frame for all animations. It can't be bigger than the smaller begin frame of all animations
  41994. * @param endFrame defines the new end frame for all animations. It can't be smaller than the larger end frame of all animations
  41995. */
  41996. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  41997. beginFrame = Math.min(beginFrame, this._from);
  41998. endFrame = Math.min(endFrame, this._to);
  41999. for (var index = 0; index < this._targetedAnimations.length; index++) {
  42000. var targetedAnimation = this._targetedAnimations[index];
  42001. var keys = targetedAnimation.animation.getKeys();
  42002. var startKey = keys[0];
  42003. var endKey = keys[keys.length - 1];
  42004. if (startKey.frame > beginFrame) {
  42005. var newKey = {
  42006. frame: beginFrame,
  42007. value: startKey.value,
  42008. inTangent: startKey.inTangent,
  42009. outTangent: startKey.outTangent
  42010. };
  42011. keys.splice(0, 0, newKey);
  42012. }
  42013. if (endKey.frame < endFrame) {
  42014. var newKey = {
  42015. frame: endFrame,
  42016. value: endKey.value,
  42017. inTangent: startKey.outTangent,
  42018. outTangent: startKey.outTangent
  42019. };
  42020. keys.push(newKey);
  42021. }
  42022. }
  42023. return this;
  42024. };
  42025. /**
  42026. * Start all animations on given targets
  42027. * @param loop defines if animations must loop
  42028. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  42029. */
  42030. AnimationGroup.prototype.start = function (loop, speedRatio) {
  42031. var _this = this;
  42032. if (loop === void 0) { loop = false; }
  42033. if (speedRatio === void 0) { speedRatio = 1; }
  42034. if (this._isStarted || this._targetedAnimations.length === 0) {
  42035. return this;
  42036. }
  42037. var _loop_1 = function () {
  42038. var targetedAnimation = this_1._targetedAnimations[index];
  42039. this_1._animatables.push(this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], this_1._from, this_1._to, loop, speedRatio, function () {
  42040. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  42041. }));
  42042. };
  42043. var this_1 = this;
  42044. for (var index = 0; index < this._targetedAnimations.length; index++) {
  42045. _loop_1();
  42046. }
  42047. this._speedRatio = speedRatio;
  42048. this._isStarted = true;
  42049. return this;
  42050. };
  42051. /**
  42052. * Pause all animations
  42053. */
  42054. AnimationGroup.prototype.pause = function () {
  42055. if (!this._isStarted) {
  42056. return this;
  42057. }
  42058. for (var index = 0; index < this._animatables.length; index++) {
  42059. var animatable = this._animatables[index];
  42060. animatable.pause();
  42061. }
  42062. return this;
  42063. };
  42064. /**
  42065. * Play all animations to initial state
  42066. * This function will start() the animations if they were not started or will restart() them if they were paused
  42067. * @param loop defines if animations must loop
  42068. */
  42069. AnimationGroup.prototype.play = function (loop) {
  42070. if (this.isStarted) {
  42071. if (loop !== undefined) {
  42072. for (var index = 0; index < this._animatables.length; index++) {
  42073. var animatable = this._animatables[index];
  42074. animatable.loopAnimation = loop;
  42075. }
  42076. }
  42077. this.restart();
  42078. }
  42079. else {
  42080. this.start(loop);
  42081. }
  42082. return this;
  42083. };
  42084. /**
  42085. * Reset all animations to initial state
  42086. */
  42087. AnimationGroup.prototype.reset = function () {
  42088. if (!this._isStarted) {
  42089. return this;
  42090. }
  42091. for (var index = 0; index < this._animatables.length; index++) {
  42092. var animatable = this._animatables[index];
  42093. animatable.reset();
  42094. }
  42095. return this;
  42096. };
  42097. /**
  42098. * Restart animations from key 0
  42099. */
  42100. AnimationGroup.prototype.restart = function () {
  42101. if (!this._isStarted) {
  42102. return this;
  42103. }
  42104. for (var index = 0; index < this._animatables.length; index++) {
  42105. var animatable = this._animatables[index];
  42106. animatable.restart();
  42107. }
  42108. return this;
  42109. };
  42110. /**
  42111. * Stop all animations
  42112. */
  42113. AnimationGroup.prototype.stop = function () {
  42114. if (!this._isStarted) {
  42115. return this;
  42116. }
  42117. for (var index = 0; index < this._animatables.length; index++) {
  42118. var animatable = this._animatables[index];
  42119. animatable.stop();
  42120. }
  42121. this._isStarted = false;
  42122. return this;
  42123. };
  42124. /**
  42125. * Dispose all associated resources
  42126. */
  42127. AnimationGroup.prototype.dispose = function () {
  42128. this._targetedAnimations = [];
  42129. this._animatables = [];
  42130. var index = this._scene.animationGroups.indexOf(this);
  42131. if (index > -1) {
  42132. this._scene.animationGroups.splice(index, 1);
  42133. }
  42134. };
  42135. return AnimationGroup;
  42136. }());
  42137. BABYLON.AnimationGroup = AnimationGroup;
  42138. })(BABYLON || (BABYLON = {}));
  42139. //# sourceMappingURL=babylon.animationGroup.js.map
  42140. var BABYLON;
  42141. (function (BABYLON) {
  42142. var RuntimeAnimation = /** @class */ (function () {
  42143. function RuntimeAnimation(target, animation) {
  42144. this._offsetsCache = {};
  42145. this._highLimitsCache = {};
  42146. this._stopped = false;
  42147. this._blendingFactor = 0;
  42148. this._ratioOffset = 0;
  42149. this._animation = animation;
  42150. this._target = target;
  42151. animation._runtimeAnimations.push(this);
  42152. }
  42153. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  42154. get: function () {
  42155. return this._animation;
  42156. },
  42157. enumerable: true,
  42158. configurable: true
  42159. });
  42160. RuntimeAnimation.prototype.reset = function () {
  42161. this._offsetsCache = {};
  42162. this._highLimitsCache = {};
  42163. this.currentFrame = 0;
  42164. this._blendingFactor = 0;
  42165. this._originalBlendValue = null;
  42166. };
  42167. RuntimeAnimation.prototype.isStopped = function () {
  42168. return this._stopped;
  42169. };
  42170. RuntimeAnimation.prototype.dispose = function () {
  42171. var index = this._animation.runtimeAnimations.indexOf(this);
  42172. if (index > -1) {
  42173. this._animation.runtimeAnimations.splice(index, 1);
  42174. }
  42175. };
  42176. RuntimeAnimation.prototype._getKeyValue = function (value) {
  42177. if (typeof value === "function") {
  42178. return value();
  42179. }
  42180. return value;
  42181. };
  42182. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  42183. if (loopMode === BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  42184. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  42185. }
  42186. this.currentFrame = currentFrame;
  42187. var keys = this._animation.getKeys();
  42188. // Try to get a hash to find the right key
  42189. 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));
  42190. if (keys[startKeyIndex].frame >= currentFrame) {
  42191. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  42192. startKeyIndex--;
  42193. }
  42194. }
  42195. for (var key = startKeyIndex; key < keys.length; key++) {
  42196. var endKey = keys[key + 1];
  42197. if (endKey.frame >= currentFrame) {
  42198. var startKey = keys[key];
  42199. var startValue = this._getKeyValue(startKey.value);
  42200. var endValue = this._getKeyValue(endKey.value);
  42201. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  42202. var frameDelta = endKey.frame - startKey.frame;
  42203. // gradient : percent of currentFrame between the frame inf and the frame sup
  42204. var gradient = (currentFrame - startKey.frame) / frameDelta;
  42205. // check for easingFunction and correction of gradient
  42206. var easingFunction = this._animation.getEasingFunction();
  42207. if (easingFunction != null) {
  42208. gradient = easingFunction.ease(gradient);
  42209. }
  42210. switch (this._animation.dataType) {
  42211. // Float
  42212. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  42213. var floatValue = useTangent ? this._animation.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this._animation.floatInterpolateFunction(startValue, endValue, gradient);
  42214. switch (loopMode) {
  42215. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  42216. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  42217. return floatValue;
  42218. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  42219. return offsetValue * repeatCount + floatValue;
  42220. }
  42221. break;
  42222. // Quaternion
  42223. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  42224. var quatValue = useTangent ? this._animation.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.quaternionInterpolateFunction(startValue, endValue, gradient);
  42225. switch (loopMode) {
  42226. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  42227. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  42228. return quatValue;
  42229. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  42230. return quatValue.add(offsetValue.scale(repeatCount));
  42231. }
  42232. return quatValue;
  42233. // Vector3
  42234. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  42235. var vec3Value = useTangent ? this._animation.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector3InterpolateFunction(startValue, endValue, gradient);
  42236. switch (loopMode) {
  42237. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  42238. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  42239. return vec3Value;
  42240. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  42241. return vec3Value.add(offsetValue.scale(repeatCount));
  42242. }
  42243. // Vector2
  42244. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  42245. var vec2Value = useTangent ? this._animation.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector2InterpolateFunction(startValue, endValue, gradient);
  42246. switch (loopMode) {
  42247. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  42248. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  42249. return vec2Value;
  42250. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  42251. return vec2Value.add(offsetValue.scale(repeatCount));
  42252. }
  42253. // Size
  42254. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  42255. switch (loopMode) {
  42256. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  42257. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  42258. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient);
  42259. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  42260. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  42261. }
  42262. // Color3
  42263. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  42264. switch (loopMode) {
  42265. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  42266. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  42267. return this._animation.color3InterpolateFunction(startValue, endValue, gradient);
  42268. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  42269. return this._animation.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  42270. }
  42271. // Matrix
  42272. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  42273. switch (loopMode) {
  42274. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  42275. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  42276. if (BABYLON.Animation.AllowMatricesInterpolation) {
  42277. return this._animation.matrixInterpolateFunction(startValue, endValue, gradient);
  42278. }
  42279. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  42280. return startValue;
  42281. }
  42282. default:
  42283. break;
  42284. }
  42285. break;
  42286. }
  42287. }
  42288. return this._getKeyValue(keys[keys.length - 1].value);
  42289. };
  42290. RuntimeAnimation.prototype.setValue = function (currentValue, blend) {
  42291. if (blend === void 0) { blend = false; }
  42292. // Set value
  42293. var path;
  42294. var destination;
  42295. var targetPropertyPath = this._animation.targetPropertyPath;
  42296. if (targetPropertyPath.length > 1) {
  42297. var property = this._target[targetPropertyPath[0]];
  42298. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  42299. property = property[targetPropertyPath[index]];
  42300. }
  42301. path = targetPropertyPath[targetPropertyPath.length - 1];
  42302. destination = property;
  42303. }
  42304. else {
  42305. path = targetPropertyPath[0];
  42306. destination = this._target;
  42307. }
  42308. // Blending
  42309. if (this._animation.enableBlending && this._blendingFactor <= 1.0) {
  42310. if (!this._originalBlendValue) {
  42311. if (destination[path].clone) {
  42312. this._originalBlendValue = destination[path].clone();
  42313. }
  42314. else {
  42315. this._originalBlendValue = destination[path];
  42316. }
  42317. }
  42318. if (this._originalBlendValue.prototype) {
  42319. if (this._originalBlendValue.prototype.Lerp) {
  42320. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  42321. }
  42322. else {
  42323. destination[path] = currentValue;
  42324. }
  42325. }
  42326. else if (this._originalBlendValue.m) {
  42327. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  42328. }
  42329. else {
  42330. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  42331. }
  42332. this._blendingFactor += this._animation.blendingSpeed;
  42333. }
  42334. else {
  42335. destination[path] = currentValue;
  42336. }
  42337. if (this._target.markAsDirty) {
  42338. this._target.markAsDirty(this._animation.targetProperty);
  42339. }
  42340. };
  42341. RuntimeAnimation.prototype.goToFrame = function (frame) {
  42342. var keys = this._animation.getKeys();
  42343. if (frame < keys[0].frame) {
  42344. frame = keys[0].frame;
  42345. }
  42346. else if (frame > keys[keys.length - 1].frame) {
  42347. frame = keys[keys.length - 1].frame;
  42348. }
  42349. var currentValue = this._interpolate(frame, 0, this._animation.loopMode);
  42350. this.setValue(currentValue);
  42351. };
  42352. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  42353. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  42354. this._ratioOffset = this._previousRatio - newRatio;
  42355. };
  42356. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  42357. if (blend === void 0) { blend = false; }
  42358. var targetPropertyPath = this._animation.targetPropertyPath;
  42359. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  42360. this._stopped = true;
  42361. return false;
  42362. }
  42363. var returnValue = true;
  42364. var keys = this._animation.getKeys();
  42365. // Adding a start key at frame 0 if missing
  42366. if (keys[0].frame !== 0) {
  42367. var newKey = { frame: 0, value: keys[0].value };
  42368. keys.splice(0, 0, newKey);
  42369. }
  42370. // Check limits
  42371. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  42372. from = keys[0].frame;
  42373. }
  42374. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  42375. to = keys[keys.length - 1].frame;
  42376. }
  42377. //to and from cannot be the same key
  42378. if (from === to) {
  42379. if (from > keys[0].frame) {
  42380. from--;
  42381. }
  42382. else if (to < keys[keys.length - 1].frame) {
  42383. to++;
  42384. }
  42385. }
  42386. // Compute ratio
  42387. var range = to - from;
  42388. var offsetValue;
  42389. // ratio represents the frame delta between from and to
  42390. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  42391. var highLimitValue = 0;
  42392. this._previousDelay = delay;
  42393. this._previousRatio = ratio;
  42394. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  42395. returnValue = false;
  42396. highLimitValue = this._getKeyValue(keys[keys.length - 1].value);
  42397. }
  42398. else {
  42399. // Get max value if required
  42400. if (this._animation.loopMode !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  42401. var keyOffset = to.toString() + from.toString();
  42402. if (!this._offsetsCache[keyOffset]) {
  42403. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  42404. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  42405. switch (this._animation.dataType) {
  42406. // Float
  42407. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  42408. this._offsetsCache[keyOffset] = toValue - fromValue;
  42409. break;
  42410. // Quaternion
  42411. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  42412. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  42413. break;
  42414. // Vector3
  42415. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  42416. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  42417. // Vector2
  42418. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  42419. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  42420. // Size
  42421. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  42422. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  42423. // Color3
  42424. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  42425. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  42426. default:
  42427. break;
  42428. }
  42429. this._highLimitsCache[keyOffset] = toValue;
  42430. }
  42431. highLimitValue = this._highLimitsCache[keyOffset];
  42432. offsetValue = this._offsetsCache[keyOffset];
  42433. }
  42434. }
  42435. if (offsetValue === undefined) {
  42436. switch (this._animation.dataType) {
  42437. // Float
  42438. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  42439. offsetValue = 0;
  42440. break;
  42441. // Quaternion
  42442. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  42443. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  42444. break;
  42445. // Vector3
  42446. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  42447. offsetValue = BABYLON.Vector3.Zero();
  42448. break;
  42449. // Vector2
  42450. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  42451. offsetValue = BABYLON.Vector2.Zero();
  42452. break;
  42453. // Size
  42454. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  42455. offsetValue = BABYLON.Size.Zero();
  42456. break;
  42457. // Color3
  42458. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  42459. offsetValue = BABYLON.Color3.Black();
  42460. }
  42461. }
  42462. // Compute value
  42463. var repeatCount = (ratio / range) >> 0;
  42464. var currentFrame = returnValue ? from + ratio % range : to;
  42465. var currentValue = this._interpolate(currentFrame, repeatCount, this._animation.loopMode, offsetValue, highLimitValue);
  42466. // Set value
  42467. this.setValue(currentValue);
  42468. // Check events
  42469. var events = this._animation.getEvents();
  42470. for (var index = 0; index < events.length; index++) {
  42471. // Make sure current frame has passed event frame and that event frame is within the current range
  42472. // Also, handle both forward and reverse animations
  42473. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  42474. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  42475. var event = events[index];
  42476. if (!event.isDone) {
  42477. // If event should be done only once, remove it.
  42478. if (event.onlyOnce) {
  42479. events.splice(index, 1);
  42480. index--;
  42481. }
  42482. event.isDone = true;
  42483. event.action();
  42484. } // Don't do anything if the event has already be done.
  42485. }
  42486. else if (events[index].isDone && !events[index].onlyOnce) {
  42487. // reset event, the animation is looping
  42488. events[index].isDone = false;
  42489. }
  42490. }
  42491. if (!returnValue) {
  42492. this._stopped = true;
  42493. }
  42494. return returnValue;
  42495. };
  42496. return RuntimeAnimation;
  42497. }());
  42498. BABYLON.RuntimeAnimation = RuntimeAnimation;
  42499. })(BABYLON || (BABYLON = {}));
  42500. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  42501. var BABYLON;
  42502. (function (BABYLON) {
  42503. var Animatable = /** @class */ (function () {
  42504. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  42505. if (fromFrame === void 0) { fromFrame = 0; }
  42506. if (toFrame === void 0) { toFrame = 100; }
  42507. if (loopAnimation === void 0) { loopAnimation = false; }
  42508. if (speedRatio === void 0) { speedRatio = 1.0; }
  42509. this.target = target;
  42510. this.fromFrame = fromFrame;
  42511. this.toFrame = toFrame;
  42512. this.loopAnimation = loopAnimation;
  42513. this.onAnimationEnd = onAnimationEnd;
  42514. this._localDelayOffset = null;
  42515. this._pausedDelay = null;
  42516. this._runtimeAnimations = new Array();
  42517. this._paused = false;
  42518. this._speedRatio = 1;
  42519. this.animationStarted = false;
  42520. if (animations) {
  42521. this.appendAnimations(target, animations);
  42522. }
  42523. this._speedRatio = speedRatio;
  42524. this._scene = scene;
  42525. scene._activeAnimatables.push(this);
  42526. }
  42527. Object.defineProperty(Animatable.prototype, "speedRatio", {
  42528. get: function () {
  42529. return this._speedRatio;
  42530. },
  42531. set: function (value) {
  42532. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  42533. var animation = this._runtimeAnimations[index];
  42534. animation._prepareForSpeedRatioChange(value);
  42535. }
  42536. this._speedRatio = value;
  42537. },
  42538. enumerable: true,
  42539. configurable: true
  42540. });
  42541. // Methods
  42542. Animatable.prototype.getAnimations = function () {
  42543. return this._runtimeAnimations;
  42544. };
  42545. Animatable.prototype.appendAnimations = function (target, animations) {
  42546. for (var index = 0; index < animations.length; index++) {
  42547. var animation = animations[index];
  42548. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation));
  42549. }
  42550. };
  42551. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  42552. var runtimeAnimations = this._runtimeAnimations;
  42553. for (var index = 0; index < runtimeAnimations.length; index++) {
  42554. if (runtimeAnimations[index].animation.targetProperty === property) {
  42555. return runtimeAnimations[index].animation;
  42556. }
  42557. }
  42558. return null;
  42559. };
  42560. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  42561. var runtimeAnimations = this._runtimeAnimations;
  42562. for (var index = 0; index < runtimeAnimations.length; index++) {
  42563. if (runtimeAnimations[index].animation.targetProperty === property) {
  42564. return runtimeAnimations[index];
  42565. }
  42566. }
  42567. return null;
  42568. };
  42569. Animatable.prototype.reset = function () {
  42570. var runtimeAnimations = this._runtimeAnimations;
  42571. for (var index = 0; index < runtimeAnimations.length; index++) {
  42572. runtimeAnimations[index].reset();
  42573. }
  42574. // Reset to original value
  42575. for (index = 0; index < runtimeAnimations.length; index++) {
  42576. var animation = runtimeAnimations[index];
  42577. animation.animate(0, this.fromFrame, this.toFrame, false, this._speedRatio);
  42578. }
  42579. this._localDelayOffset = null;
  42580. this._pausedDelay = null;
  42581. };
  42582. Animatable.prototype.enableBlending = function (blendingSpeed) {
  42583. var runtimeAnimations = this._runtimeAnimations;
  42584. for (var index = 0; index < runtimeAnimations.length; index++) {
  42585. runtimeAnimations[index].animation.enableBlending = true;
  42586. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  42587. }
  42588. };
  42589. Animatable.prototype.disableBlending = function () {
  42590. var runtimeAnimations = this._runtimeAnimations;
  42591. for (var index = 0; index < runtimeAnimations.length; index++) {
  42592. runtimeAnimations[index].animation.enableBlending = false;
  42593. }
  42594. };
  42595. Animatable.prototype.goToFrame = function (frame) {
  42596. var runtimeAnimations = this._runtimeAnimations;
  42597. if (runtimeAnimations[0]) {
  42598. var fps = runtimeAnimations[0].animation.framePerSecond;
  42599. var currentFrame = runtimeAnimations[0].currentFrame;
  42600. var adjustTime = frame - currentFrame;
  42601. var delay = adjustTime * 1000 / fps;
  42602. if (this._localDelayOffset === null) {
  42603. this._localDelayOffset = 0;
  42604. }
  42605. this._localDelayOffset -= delay;
  42606. }
  42607. for (var index = 0; index < runtimeAnimations.length; index++) {
  42608. runtimeAnimations[index].goToFrame(frame);
  42609. }
  42610. };
  42611. Animatable.prototype.pause = function () {
  42612. if (this._paused) {
  42613. return;
  42614. }
  42615. this._paused = true;
  42616. };
  42617. Animatable.prototype.restart = function () {
  42618. this._paused = false;
  42619. };
  42620. Animatable.prototype.stop = function (animationName) {
  42621. if (animationName) {
  42622. var idx = this._scene._activeAnimatables.indexOf(this);
  42623. if (idx > -1) {
  42624. var runtimeAnimations = this._runtimeAnimations;
  42625. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  42626. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  42627. continue;
  42628. }
  42629. runtimeAnimations[index].dispose();
  42630. runtimeAnimations.splice(index, 1);
  42631. }
  42632. if (runtimeAnimations.length == 0) {
  42633. this._scene._activeAnimatables.splice(idx, 1);
  42634. if (this.onAnimationEnd) {
  42635. this.onAnimationEnd();
  42636. }
  42637. }
  42638. }
  42639. }
  42640. else {
  42641. var index = this._scene._activeAnimatables.indexOf(this);
  42642. if (index > -1) {
  42643. this._scene._activeAnimatables.splice(index, 1);
  42644. var runtimeAnimations = this._runtimeAnimations;
  42645. for (var index = 0; index < runtimeAnimations.length; index++) {
  42646. runtimeAnimations[index].dispose();
  42647. }
  42648. if (this.onAnimationEnd) {
  42649. this.onAnimationEnd();
  42650. }
  42651. }
  42652. }
  42653. };
  42654. Animatable.prototype._animate = function (delay) {
  42655. if (this._paused) {
  42656. this.animationStarted = false;
  42657. if (this._pausedDelay === null) {
  42658. this._pausedDelay = delay;
  42659. }
  42660. return true;
  42661. }
  42662. if (this._localDelayOffset === null) {
  42663. this._localDelayOffset = delay;
  42664. }
  42665. else if (this._pausedDelay !== null) {
  42666. this._localDelayOffset += delay - this._pausedDelay;
  42667. this._pausedDelay = null;
  42668. }
  42669. // Animating
  42670. var running = false;
  42671. var runtimeAnimations = this._runtimeAnimations;
  42672. var index;
  42673. for (index = 0; index < runtimeAnimations.length; index++) {
  42674. var animation = runtimeAnimations[index];
  42675. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio);
  42676. running = running || isRunning;
  42677. }
  42678. this.animationStarted = running;
  42679. if (!running) {
  42680. // Remove from active animatables
  42681. index = this._scene._activeAnimatables.indexOf(this);
  42682. this._scene._activeAnimatables.splice(index, 1);
  42683. // Dispose all runtime animations
  42684. for (index = 0; index < runtimeAnimations.length; index++) {
  42685. runtimeAnimations[index].dispose();
  42686. }
  42687. }
  42688. if (!running && this.onAnimationEnd) {
  42689. this.onAnimationEnd();
  42690. this.onAnimationEnd = null;
  42691. }
  42692. return running;
  42693. };
  42694. return Animatable;
  42695. }());
  42696. BABYLON.Animatable = Animatable;
  42697. })(BABYLON || (BABYLON = {}));
  42698. //# sourceMappingURL=babylon.animatable.js.map
  42699. var BABYLON;
  42700. (function (BABYLON) {
  42701. var EasingFunction = /** @class */ (function () {
  42702. function EasingFunction() {
  42703. // Properties
  42704. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  42705. }
  42706. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  42707. get: function () {
  42708. return EasingFunction._EASINGMODE_EASEIN;
  42709. },
  42710. enumerable: true,
  42711. configurable: true
  42712. });
  42713. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  42714. get: function () {
  42715. return EasingFunction._EASINGMODE_EASEOUT;
  42716. },
  42717. enumerable: true,
  42718. configurable: true
  42719. });
  42720. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  42721. get: function () {
  42722. return EasingFunction._EASINGMODE_EASEINOUT;
  42723. },
  42724. enumerable: true,
  42725. configurable: true
  42726. });
  42727. EasingFunction.prototype.setEasingMode = function (easingMode) {
  42728. var n = Math.min(Math.max(easingMode, 0), 2);
  42729. this._easingMode = n;
  42730. };
  42731. EasingFunction.prototype.getEasingMode = function () {
  42732. return this._easingMode;
  42733. };
  42734. EasingFunction.prototype.easeInCore = function (gradient) {
  42735. throw new Error('You must implement this method');
  42736. };
  42737. EasingFunction.prototype.ease = function (gradient) {
  42738. switch (this._easingMode) {
  42739. case EasingFunction.EASINGMODE_EASEIN:
  42740. return this.easeInCore(gradient);
  42741. case EasingFunction.EASINGMODE_EASEOUT:
  42742. return (1 - this.easeInCore(1 - gradient));
  42743. }
  42744. if (gradient >= 0.5) {
  42745. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  42746. }
  42747. return (this.easeInCore(gradient * 2) * 0.5);
  42748. };
  42749. //Statics
  42750. EasingFunction._EASINGMODE_EASEIN = 0;
  42751. EasingFunction._EASINGMODE_EASEOUT = 1;
  42752. EasingFunction._EASINGMODE_EASEINOUT = 2;
  42753. return EasingFunction;
  42754. }());
  42755. BABYLON.EasingFunction = EasingFunction;
  42756. var CircleEase = /** @class */ (function (_super) {
  42757. __extends(CircleEase, _super);
  42758. function CircleEase() {
  42759. return _super !== null && _super.apply(this, arguments) || this;
  42760. }
  42761. CircleEase.prototype.easeInCore = function (gradient) {
  42762. gradient = Math.max(0, Math.min(1, gradient));
  42763. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  42764. };
  42765. return CircleEase;
  42766. }(EasingFunction));
  42767. BABYLON.CircleEase = CircleEase;
  42768. var BackEase = /** @class */ (function (_super) {
  42769. __extends(BackEase, _super);
  42770. function BackEase(amplitude) {
  42771. if (amplitude === void 0) { amplitude = 1; }
  42772. var _this = _super.call(this) || this;
  42773. _this.amplitude = amplitude;
  42774. return _this;
  42775. }
  42776. BackEase.prototype.easeInCore = function (gradient) {
  42777. var num = Math.max(0, this.amplitude);
  42778. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  42779. };
  42780. return BackEase;
  42781. }(EasingFunction));
  42782. BABYLON.BackEase = BackEase;
  42783. var BounceEase = /** @class */ (function (_super) {
  42784. __extends(BounceEase, _super);
  42785. function BounceEase(bounces, bounciness) {
  42786. if (bounces === void 0) { bounces = 3; }
  42787. if (bounciness === void 0) { bounciness = 2; }
  42788. var _this = _super.call(this) || this;
  42789. _this.bounces = bounces;
  42790. _this.bounciness = bounciness;
  42791. return _this;
  42792. }
  42793. BounceEase.prototype.easeInCore = function (gradient) {
  42794. var y = Math.max(0.0, this.bounces);
  42795. var bounciness = this.bounciness;
  42796. if (bounciness <= 1.0) {
  42797. bounciness = 1.001;
  42798. }
  42799. var num9 = Math.pow(bounciness, y);
  42800. var num5 = 1.0 - bounciness;
  42801. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  42802. var num15 = gradient * num4;
  42803. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  42804. var num3 = Math.floor(num65);
  42805. var num13 = num3 + 1.0;
  42806. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  42807. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  42808. var num7 = (num8 + num12) * 0.5;
  42809. var num6 = gradient - num7;
  42810. var num2 = num7 - num8;
  42811. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  42812. };
  42813. return BounceEase;
  42814. }(EasingFunction));
  42815. BABYLON.BounceEase = BounceEase;
  42816. var CubicEase = /** @class */ (function (_super) {
  42817. __extends(CubicEase, _super);
  42818. function CubicEase() {
  42819. return _super !== null && _super.apply(this, arguments) || this;
  42820. }
  42821. CubicEase.prototype.easeInCore = function (gradient) {
  42822. return (gradient * gradient * gradient);
  42823. };
  42824. return CubicEase;
  42825. }(EasingFunction));
  42826. BABYLON.CubicEase = CubicEase;
  42827. var ElasticEase = /** @class */ (function (_super) {
  42828. __extends(ElasticEase, _super);
  42829. function ElasticEase(oscillations, springiness) {
  42830. if (oscillations === void 0) { oscillations = 3; }
  42831. if (springiness === void 0) { springiness = 3; }
  42832. var _this = _super.call(this) || this;
  42833. _this.oscillations = oscillations;
  42834. _this.springiness = springiness;
  42835. return _this;
  42836. }
  42837. ElasticEase.prototype.easeInCore = function (gradient) {
  42838. var num2;
  42839. var num3 = Math.max(0.0, this.oscillations);
  42840. var num = Math.max(0.0, this.springiness);
  42841. if (num == 0) {
  42842. num2 = gradient;
  42843. }
  42844. else {
  42845. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  42846. }
  42847. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  42848. };
  42849. return ElasticEase;
  42850. }(EasingFunction));
  42851. BABYLON.ElasticEase = ElasticEase;
  42852. var ExponentialEase = /** @class */ (function (_super) {
  42853. __extends(ExponentialEase, _super);
  42854. function ExponentialEase(exponent) {
  42855. if (exponent === void 0) { exponent = 2; }
  42856. var _this = _super.call(this) || this;
  42857. _this.exponent = exponent;
  42858. return _this;
  42859. }
  42860. ExponentialEase.prototype.easeInCore = function (gradient) {
  42861. if (this.exponent <= 0) {
  42862. return gradient;
  42863. }
  42864. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  42865. };
  42866. return ExponentialEase;
  42867. }(EasingFunction));
  42868. BABYLON.ExponentialEase = ExponentialEase;
  42869. var PowerEase = /** @class */ (function (_super) {
  42870. __extends(PowerEase, _super);
  42871. function PowerEase(power) {
  42872. if (power === void 0) { power = 2; }
  42873. var _this = _super.call(this) || this;
  42874. _this.power = power;
  42875. return _this;
  42876. }
  42877. PowerEase.prototype.easeInCore = function (gradient) {
  42878. var y = Math.max(0.0, this.power);
  42879. return Math.pow(gradient, y);
  42880. };
  42881. return PowerEase;
  42882. }(EasingFunction));
  42883. BABYLON.PowerEase = PowerEase;
  42884. var QuadraticEase = /** @class */ (function (_super) {
  42885. __extends(QuadraticEase, _super);
  42886. function QuadraticEase() {
  42887. return _super !== null && _super.apply(this, arguments) || this;
  42888. }
  42889. QuadraticEase.prototype.easeInCore = function (gradient) {
  42890. return (gradient * gradient);
  42891. };
  42892. return QuadraticEase;
  42893. }(EasingFunction));
  42894. BABYLON.QuadraticEase = QuadraticEase;
  42895. var QuarticEase = /** @class */ (function (_super) {
  42896. __extends(QuarticEase, _super);
  42897. function QuarticEase() {
  42898. return _super !== null && _super.apply(this, arguments) || this;
  42899. }
  42900. QuarticEase.prototype.easeInCore = function (gradient) {
  42901. return (gradient * gradient * gradient * gradient);
  42902. };
  42903. return QuarticEase;
  42904. }(EasingFunction));
  42905. BABYLON.QuarticEase = QuarticEase;
  42906. var QuinticEase = /** @class */ (function (_super) {
  42907. __extends(QuinticEase, _super);
  42908. function QuinticEase() {
  42909. return _super !== null && _super.apply(this, arguments) || this;
  42910. }
  42911. QuinticEase.prototype.easeInCore = function (gradient) {
  42912. return (gradient * gradient * gradient * gradient * gradient);
  42913. };
  42914. return QuinticEase;
  42915. }(EasingFunction));
  42916. BABYLON.QuinticEase = QuinticEase;
  42917. var SineEase = /** @class */ (function (_super) {
  42918. __extends(SineEase, _super);
  42919. function SineEase() {
  42920. return _super !== null && _super.apply(this, arguments) || this;
  42921. }
  42922. SineEase.prototype.easeInCore = function (gradient) {
  42923. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  42924. };
  42925. return SineEase;
  42926. }(EasingFunction));
  42927. BABYLON.SineEase = SineEase;
  42928. var BezierCurveEase = /** @class */ (function (_super) {
  42929. __extends(BezierCurveEase, _super);
  42930. function BezierCurveEase(x1, y1, x2, y2) {
  42931. if (x1 === void 0) { x1 = 0; }
  42932. if (y1 === void 0) { y1 = 0; }
  42933. if (x2 === void 0) { x2 = 1; }
  42934. if (y2 === void 0) { y2 = 1; }
  42935. var _this = _super.call(this) || this;
  42936. _this.x1 = x1;
  42937. _this.y1 = y1;
  42938. _this.x2 = x2;
  42939. _this.y2 = y2;
  42940. return _this;
  42941. }
  42942. BezierCurveEase.prototype.easeInCore = function (gradient) {
  42943. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  42944. };
  42945. return BezierCurveEase;
  42946. }(EasingFunction));
  42947. BABYLON.BezierCurveEase = BezierCurveEase;
  42948. })(BABYLON || (BABYLON = {}));
  42949. //# sourceMappingURL=babylon.easing.js.map
  42950. var BABYLON;
  42951. (function (BABYLON) {
  42952. var Condition = /** @class */ (function () {
  42953. function Condition(actionManager) {
  42954. this._actionManager = actionManager;
  42955. }
  42956. Condition.prototype.isValid = function () {
  42957. return true;
  42958. };
  42959. Condition.prototype._getProperty = function (propertyPath) {
  42960. return this._actionManager._getProperty(propertyPath);
  42961. };
  42962. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  42963. return this._actionManager._getEffectiveTarget(target, propertyPath);
  42964. };
  42965. Condition.prototype.serialize = function () {
  42966. };
  42967. Condition.prototype._serialize = function (serializedCondition) {
  42968. return {
  42969. type: 2,
  42970. children: [],
  42971. name: serializedCondition.name,
  42972. properties: serializedCondition.properties
  42973. };
  42974. };
  42975. return Condition;
  42976. }());
  42977. BABYLON.Condition = Condition;
  42978. var ValueCondition = /** @class */ (function (_super) {
  42979. __extends(ValueCondition, _super);
  42980. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  42981. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  42982. var _this = _super.call(this, actionManager) || this;
  42983. _this.propertyPath = propertyPath;
  42984. _this.value = value;
  42985. _this.operator = operator;
  42986. _this._target = target;
  42987. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  42988. _this._property = _this._getProperty(_this.propertyPath);
  42989. return _this;
  42990. }
  42991. Object.defineProperty(ValueCondition, "IsEqual", {
  42992. get: function () {
  42993. return ValueCondition._IsEqual;
  42994. },
  42995. enumerable: true,
  42996. configurable: true
  42997. });
  42998. Object.defineProperty(ValueCondition, "IsDifferent", {
  42999. get: function () {
  43000. return ValueCondition._IsDifferent;
  43001. },
  43002. enumerable: true,
  43003. configurable: true
  43004. });
  43005. Object.defineProperty(ValueCondition, "IsGreater", {
  43006. get: function () {
  43007. return ValueCondition._IsGreater;
  43008. },
  43009. enumerable: true,
  43010. configurable: true
  43011. });
  43012. Object.defineProperty(ValueCondition, "IsLesser", {
  43013. get: function () {
  43014. return ValueCondition._IsLesser;
  43015. },
  43016. enumerable: true,
  43017. configurable: true
  43018. });
  43019. // Methods
  43020. ValueCondition.prototype.isValid = function () {
  43021. switch (this.operator) {
  43022. case ValueCondition.IsGreater:
  43023. return this._effectiveTarget[this._property] > this.value;
  43024. case ValueCondition.IsLesser:
  43025. return this._effectiveTarget[this._property] < this.value;
  43026. case ValueCondition.IsEqual:
  43027. case ValueCondition.IsDifferent:
  43028. var check;
  43029. if (this.value.equals) {
  43030. check = this.value.equals(this._effectiveTarget[this._property]);
  43031. }
  43032. else {
  43033. check = this.value === this._effectiveTarget[this._property];
  43034. }
  43035. return this.operator === ValueCondition.IsEqual ? check : !check;
  43036. }
  43037. return false;
  43038. };
  43039. ValueCondition.prototype.serialize = function () {
  43040. return this._serialize({
  43041. name: "ValueCondition",
  43042. properties: [
  43043. BABYLON.Action._GetTargetProperty(this._target),
  43044. { name: "propertyPath", value: this.propertyPath },
  43045. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  43046. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  43047. ]
  43048. });
  43049. };
  43050. ValueCondition.GetOperatorName = function (operator) {
  43051. switch (operator) {
  43052. case ValueCondition._IsEqual: return "IsEqual";
  43053. case ValueCondition._IsDifferent: return "IsDifferent";
  43054. case ValueCondition._IsGreater: return "IsGreater";
  43055. case ValueCondition._IsLesser: return "IsLesser";
  43056. default: return "";
  43057. }
  43058. };
  43059. // Statics
  43060. ValueCondition._IsEqual = 0;
  43061. ValueCondition._IsDifferent = 1;
  43062. ValueCondition._IsGreater = 2;
  43063. ValueCondition._IsLesser = 3;
  43064. return ValueCondition;
  43065. }(Condition));
  43066. BABYLON.ValueCondition = ValueCondition;
  43067. var PredicateCondition = /** @class */ (function (_super) {
  43068. __extends(PredicateCondition, _super);
  43069. function PredicateCondition(actionManager, predicate) {
  43070. var _this = _super.call(this, actionManager) || this;
  43071. _this.predicate = predicate;
  43072. return _this;
  43073. }
  43074. PredicateCondition.prototype.isValid = function () {
  43075. return this.predicate();
  43076. };
  43077. return PredicateCondition;
  43078. }(Condition));
  43079. BABYLON.PredicateCondition = PredicateCondition;
  43080. var StateCondition = /** @class */ (function (_super) {
  43081. __extends(StateCondition, _super);
  43082. function StateCondition(actionManager, target, value) {
  43083. var _this = _super.call(this, actionManager) || this;
  43084. _this.value = value;
  43085. _this._target = target;
  43086. return _this;
  43087. }
  43088. // Methods
  43089. StateCondition.prototype.isValid = function () {
  43090. return this._target.state === this.value;
  43091. };
  43092. StateCondition.prototype.serialize = function () {
  43093. return this._serialize({
  43094. name: "StateCondition",
  43095. properties: [
  43096. BABYLON.Action._GetTargetProperty(this._target),
  43097. { name: "value", value: this.value }
  43098. ]
  43099. });
  43100. };
  43101. return StateCondition;
  43102. }(Condition));
  43103. BABYLON.StateCondition = StateCondition;
  43104. })(BABYLON || (BABYLON = {}));
  43105. //# sourceMappingURL=babylon.condition.js.map
  43106. var BABYLON;
  43107. (function (BABYLON) {
  43108. var Action = /** @class */ (function () {
  43109. function Action(triggerOptions, condition) {
  43110. this.triggerOptions = triggerOptions;
  43111. this.onBeforeExecuteObservable = new BABYLON.Observable();
  43112. if (triggerOptions.parameter) {
  43113. this.trigger = triggerOptions.trigger;
  43114. this._triggerParameter = triggerOptions.parameter;
  43115. }
  43116. else {
  43117. this.trigger = triggerOptions;
  43118. }
  43119. this._nextActiveAction = this;
  43120. this._condition = condition;
  43121. }
  43122. // Methods
  43123. Action.prototype._prepare = function () {
  43124. };
  43125. Action.prototype.getTriggerParameter = function () {
  43126. return this._triggerParameter;
  43127. };
  43128. Action.prototype._executeCurrent = function (evt) {
  43129. if (this._nextActiveAction._condition) {
  43130. var condition = this._nextActiveAction._condition;
  43131. var currentRenderId = this._actionManager.getScene().getRenderId();
  43132. // We cache the current evaluation for the current frame
  43133. if (condition._evaluationId === currentRenderId) {
  43134. if (!condition._currentResult) {
  43135. return;
  43136. }
  43137. }
  43138. else {
  43139. condition._evaluationId = currentRenderId;
  43140. if (!condition.isValid()) {
  43141. condition._currentResult = false;
  43142. return;
  43143. }
  43144. condition._currentResult = true;
  43145. }
  43146. }
  43147. this.onBeforeExecuteObservable.notifyObservers(this);
  43148. this._nextActiveAction.execute(evt);
  43149. this.skipToNextActiveAction();
  43150. };
  43151. Action.prototype.execute = function (evt) {
  43152. };
  43153. Action.prototype.skipToNextActiveAction = function () {
  43154. if (this._nextActiveAction._child) {
  43155. if (!this._nextActiveAction._child._actionManager) {
  43156. this._nextActiveAction._child._actionManager = this._actionManager;
  43157. }
  43158. this._nextActiveAction = this._nextActiveAction._child;
  43159. }
  43160. else {
  43161. this._nextActiveAction = this;
  43162. }
  43163. };
  43164. Action.prototype.then = function (action) {
  43165. this._child = action;
  43166. action._actionManager = this._actionManager;
  43167. action._prepare();
  43168. return action;
  43169. };
  43170. Action.prototype._getProperty = function (propertyPath) {
  43171. return this._actionManager._getProperty(propertyPath);
  43172. };
  43173. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  43174. return this._actionManager._getEffectiveTarget(target, propertyPath);
  43175. };
  43176. Action.prototype.serialize = function (parent) {
  43177. };
  43178. // Called by BABYLON.Action objects in serialize(...). Internal use
  43179. Action.prototype._serialize = function (serializedAction, parent) {
  43180. var serializationObject = {
  43181. type: 1,
  43182. children: [],
  43183. name: serializedAction.name,
  43184. properties: serializedAction.properties || []
  43185. };
  43186. // Serialize child
  43187. if (this._child) {
  43188. this._child.serialize(serializationObject);
  43189. }
  43190. // Check if "this" has a condition
  43191. if (this._condition) {
  43192. var serializedCondition = this._condition.serialize();
  43193. serializedCondition.children.push(serializationObject);
  43194. if (parent) {
  43195. parent.children.push(serializedCondition);
  43196. }
  43197. return serializedCondition;
  43198. }
  43199. if (parent) {
  43200. parent.children.push(serializationObject);
  43201. }
  43202. return serializationObject;
  43203. };
  43204. Action._SerializeValueAsString = function (value) {
  43205. if (typeof value === "number") {
  43206. return value.toString();
  43207. }
  43208. if (typeof value === "boolean") {
  43209. return value ? "true" : "false";
  43210. }
  43211. if (value instanceof BABYLON.Vector2) {
  43212. return value.x + ", " + value.y;
  43213. }
  43214. if (value instanceof BABYLON.Vector3) {
  43215. return value.x + ", " + value.y + ", " + value.z;
  43216. }
  43217. if (value instanceof BABYLON.Color3) {
  43218. return value.r + ", " + value.g + ", " + value.b;
  43219. }
  43220. if (value instanceof BABYLON.Color4) {
  43221. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  43222. }
  43223. return value; // string
  43224. };
  43225. Action._GetTargetProperty = function (target) {
  43226. return {
  43227. name: "target",
  43228. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  43229. : target instanceof BABYLON.Light ? "LightProperties"
  43230. : target instanceof BABYLON.Camera ? "CameraProperties"
  43231. : "SceneProperties",
  43232. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  43233. };
  43234. };
  43235. return Action;
  43236. }());
  43237. BABYLON.Action = Action;
  43238. })(BABYLON || (BABYLON = {}));
  43239. //# sourceMappingURL=babylon.action.js.map
  43240. var BABYLON;
  43241. (function (BABYLON) {
  43242. /**
  43243. * ActionEvent is the event beint sent when an action is triggered.
  43244. */
  43245. var ActionEvent = /** @class */ (function () {
  43246. /**
  43247. * @param source The mesh or sprite that triggered the action.
  43248. * @param pointerX The X mouse cursor position at the time of the event
  43249. * @param pointerY The Y mouse cursor position at the time of the event
  43250. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  43251. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  43252. */
  43253. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  43254. this.source = source;
  43255. this.pointerX = pointerX;
  43256. this.pointerY = pointerY;
  43257. this.meshUnderPointer = meshUnderPointer;
  43258. this.sourceEvent = sourceEvent;
  43259. this.additionalData = additionalData;
  43260. }
  43261. /**
  43262. * Helper function to auto-create an ActionEvent from a source mesh.
  43263. * @param source The source mesh that triggered the event
  43264. * @param evt {Event} The original (browser) event
  43265. */
  43266. ActionEvent.CreateNew = function (source, evt, additionalData) {
  43267. var scene = source.getScene();
  43268. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  43269. };
  43270. /**
  43271. * Helper function to auto-create an ActionEvent from a source mesh.
  43272. * @param source The source sprite that triggered the event
  43273. * @param scene Scene associated with the sprite
  43274. * @param evt {Event} The original (browser) event
  43275. */
  43276. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  43277. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  43278. };
  43279. /**
  43280. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  43281. * @param scene the scene where the event occurred
  43282. * @param evt {Event} The original (browser) event
  43283. */
  43284. ActionEvent.CreateNewFromScene = function (scene, evt) {
  43285. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  43286. };
  43287. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  43288. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  43289. };
  43290. return ActionEvent;
  43291. }());
  43292. BABYLON.ActionEvent = ActionEvent;
  43293. /**
  43294. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  43295. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  43296. */
  43297. var ActionManager = /** @class */ (function () {
  43298. function ActionManager(scene) {
  43299. // Members
  43300. this.actions = new Array();
  43301. this.hoverCursor = '';
  43302. this._scene = scene;
  43303. scene._actionManagers.push(this);
  43304. }
  43305. Object.defineProperty(ActionManager, "NothingTrigger", {
  43306. get: function () {
  43307. return ActionManager._NothingTrigger;
  43308. },
  43309. enumerable: true,
  43310. configurable: true
  43311. });
  43312. Object.defineProperty(ActionManager, "OnPickTrigger", {
  43313. get: function () {
  43314. return ActionManager._OnPickTrigger;
  43315. },
  43316. enumerable: true,
  43317. configurable: true
  43318. });
  43319. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  43320. get: function () {
  43321. return ActionManager._OnLeftPickTrigger;
  43322. },
  43323. enumerable: true,
  43324. configurable: true
  43325. });
  43326. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  43327. get: function () {
  43328. return ActionManager._OnRightPickTrigger;
  43329. },
  43330. enumerable: true,
  43331. configurable: true
  43332. });
  43333. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  43334. get: function () {
  43335. return ActionManager._OnCenterPickTrigger;
  43336. },
  43337. enumerable: true,
  43338. configurable: true
  43339. });
  43340. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  43341. get: function () {
  43342. return ActionManager._OnPickDownTrigger;
  43343. },
  43344. enumerable: true,
  43345. configurable: true
  43346. });
  43347. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  43348. get: function () {
  43349. return ActionManager._OnDoublePickTrigger;
  43350. },
  43351. enumerable: true,
  43352. configurable: true
  43353. });
  43354. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  43355. get: function () {
  43356. return ActionManager._OnPickUpTrigger;
  43357. },
  43358. enumerable: true,
  43359. configurable: true
  43360. });
  43361. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  43362. /// This trigger will only be raised if you also declared a OnPickDown
  43363. get: function () {
  43364. return ActionManager._OnPickOutTrigger;
  43365. },
  43366. enumerable: true,
  43367. configurable: true
  43368. });
  43369. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  43370. get: function () {
  43371. return ActionManager._OnLongPressTrigger;
  43372. },
  43373. enumerable: true,
  43374. configurable: true
  43375. });
  43376. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  43377. get: function () {
  43378. return ActionManager._OnPointerOverTrigger;
  43379. },
  43380. enumerable: true,
  43381. configurable: true
  43382. });
  43383. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  43384. get: function () {
  43385. return ActionManager._OnPointerOutTrigger;
  43386. },
  43387. enumerable: true,
  43388. configurable: true
  43389. });
  43390. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  43391. get: function () {
  43392. return ActionManager._OnEveryFrameTrigger;
  43393. },
  43394. enumerable: true,
  43395. configurable: true
  43396. });
  43397. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  43398. get: function () {
  43399. return ActionManager._OnIntersectionEnterTrigger;
  43400. },
  43401. enumerable: true,
  43402. configurable: true
  43403. });
  43404. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  43405. get: function () {
  43406. return ActionManager._OnIntersectionExitTrigger;
  43407. },
  43408. enumerable: true,
  43409. configurable: true
  43410. });
  43411. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  43412. get: function () {
  43413. return ActionManager._OnKeyDownTrigger;
  43414. },
  43415. enumerable: true,
  43416. configurable: true
  43417. });
  43418. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  43419. get: function () {
  43420. return ActionManager._OnKeyUpTrigger;
  43421. },
  43422. enumerable: true,
  43423. configurable: true
  43424. });
  43425. // Methods
  43426. ActionManager.prototype.dispose = function () {
  43427. var index = this._scene._actionManagers.indexOf(this);
  43428. for (var i = 0; i < this.actions.length; i++) {
  43429. var action = this.actions[i];
  43430. ActionManager.Triggers[action.trigger]--;
  43431. if (ActionManager.Triggers[action.trigger] === 0) {
  43432. delete ActionManager.Triggers[action.trigger];
  43433. }
  43434. }
  43435. if (index > -1) {
  43436. this._scene._actionManagers.splice(index, 1);
  43437. }
  43438. };
  43439. ActionManager.prototype.getScene = function () {
  43440. return this._scene;
  43441. };
  43442. /**
  43443. * Does this action manager handles actions of any of the given triggers
  43444. * @param {number[]} triggers - the triggers to be tested
  43445. * @return {boolean} whether one (or more) of the triggers is handeled
  43446. */
  43447. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  43448. for (var index = 0; index < this.actions.length; index++) {
  43449. var action = this.actions[index];
  43450. if (triggers.indexOf(action.trigger) > -1) {
  43451. return true;
  43452. }
  43453. }
  43454. return false;
  43455. };
  43456. /**
  43457. * Does this action manager handles actions of a given trigger
  43458. * @param {number} trigger - the trigger to be tested
  43459. * @return {boolean} whether the trigger is handeled
  43460. */
  43461. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  43462. for (var index = 0; index < this.actions.length; index++) {
  43463. var action = this.actions[index];
  43464. if (action.trigger === trigger) {
  43465. return true;
  43466. }
  43467. }
  43468. return false;
  43469. };
  43470. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  43471. /**
  43472. * Does this action manager has pointer triggers
  43473. * @return {boolean} whether or not it has pointer triggers
  43474. */
  43475. get: function () {
  43476. for (var index = 0; index < this.actions.length; index++) {
  43477. var action = this.actions[index];
  43478. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  43479. return true;
  43480. }
  43481. }
  43482. return false;
  43483. },
  43484. enumerable: true,
  43485. configurable: true
  43486. });
  43487. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  43488. /**
  43489. * Does this action manager has pick triggers
  43490. * @return {boolean} whether or not it has pick triggers
  43491. */
  43492. get: function () {
  43493. for (var index = 0; index < this.actions.length; index++) {
  43494. var action = this.actions[index];
  43495. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  43496. return true;
  43497. }
  43498. }
  43499. return false;
  43500. },
  43501. enumerable: true,
  43502. configurable: true
  43503. });
  43504. Object.defineProperty(ActionManager, "HasTriggers", {
  43505. /**
  43506. * Does exist one action manager with at least one trigger
  43507. * @return {boolean} whether or not it exists one action manager with one trigger
  43508. **/
  43509. get: function () {
  43510. for (var t in ActionManager.Triggers) {
  43511. if (ActionManager.Triggers.hasOwnProperty(t)) {
  43512. return true;
  43513. }
  43514. }
  43515. return false;
  43516. },
  43517. enumerable: true,
  43518. configurable: true
  43519. });
  43520. Object.defineProperty(ActionManager, "HasPickTriggers", {
  43521. /**
  43522. * Does exist one action manager with at least one pick trigger
  43523. * @return {boolean} whether or not it exists one action manager with one pick trigger
  43524. **/
  43525. get: function () {
  43526. for (var t in ActionManager.Triggers) {
  43527. if (ActionManager.Triggers.hasOwnProperty(t)) {
  43528. var t_int = parseInt(t);
  43529. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  43530. return true;
  43531. }
  43532. }
  43533. }
  43534. return false;
  43535. },
  43536. enumerable: true,
  43537. configurable: true
  43538. });
  43539. /**
  43540. * Does exist one action manager that handles actions of a given trigger
  43541. * @param {number} trigger - the trigger to be tested
  43542. * @return {boolean} whether the trigger is handeled by at least one action manager
  43543. **/
  43544. ActionManager.HasSpecificTrigger = function (trigger) {
  43545. for (var t in ActionManager.Triggers) {
  43546. if (ActionManager.Triggers.hasOwnProperty(t)) {
  43547. var t_int = parseInt(t);
  43548. if (t_int === trigger) {
  43549. return true;
  43550. }
  43551. }
  43552. }
  43553. return false;
  43554. };
  43555. /**
  43556. * Registers an action to this action manager
  43557. * @param {BABYLON.Action} action - the action to be registered
  43558. * @return {BABYLON.Action} the action amended (prepared) after registration
  43559. */
  43560. ActionManager.prototype.registerAction = function (action) {
  43561. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  43562. if (this.getScene().actionManager !== this) {
  43563. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  43564. return null;
  43565. }
  43566. }
  43567. this.actions.push(action);
  43568. if (ActionManager.Triggers[action.trigger]) {
  43569. ActionManager.Triggers[action.trigger]++;
  43570. }
  43571. else {
  43572. ActionManager.Triggers[action.trigger] = 1;
  43573. }
  43574. action._actionManager = this;
  43575. action._prepare();
  43576. return action;
  43577. };
  43578. /**
  43579. * Process a specific trigger
  43580. * @param {number} trigger - the trigger to process
  43581. * @param evt {BABYLON.ActionEvent} the event details to be processed
  43582. */
  43583. ActionManager.prototype.processTrigger = function (trigger, evt) {
  43584. for (var index = 0; index < this.actions.length; index++) {
  43585. var action = this.actions[index];
  43586. if (action.trigger === trigger) {
  43587. if (evt) {
  43588. if (trigger === ActionManager.OnKeyUpTrigger
  43589. || trigger === ActionManager.OnKeyDownTrigger) {
  43590. var parameter = action.getTriggerParameter();
  43591. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  43592. if (!parameter.toLowerCase) {
  43593. continue;
  43594. }
  43595. var lowerCase = parameter.toLowerCase();
  43596. if (lowerCase !== evt.sourceEvent.key) {
  43597. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  43598. var actualkey = String.fromCharCode(unicode).toLowerCase();
  43599. if (actualkey !== lowerCase) {
  43600. continue;
  43601. }
  43602. }
  43603. }
  43604. }
  43605. }
  43606. action._executeCurrent(evt);
  43607. }
  43608. }
  43609. };
  43610. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  43611. var properties = propertyPath.split(".");
  43612. for (var index = 0; index < properties.length - 1; index++) {
  43613. target = target[properties[index]];
  43614. }
  43615. return target;
  43616. };
  43617. ActionManager.prototype._getProperty = function (propertyPath) {
  43618. var properties = propertyPath.split(".");
  43619. return properties[properties.length - 1];
  43620. };
  43621. ActionManager.prototype.serialize = function (name) {
  43622. var root = {
  43623. children: new Array(),
  43624. name: name,
  43625. type: 3,
  43626. properties: new Array() // Empty for root but required
  43627. };
  43628. for (var i = 0; i < this.actions.length; i++) {
  43629. var triggerObject = {
  43630. type: 0,
  43631. children: new Array(),
  43632. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  43633. properties: new Array()
  43634. };
  43635. var triggerOptions = this.actions[i].triggerOptions;
  43636. if (triggerOptions && typeof triggerOptions !== "number") {
  43637. if (triggerOptions.parameter instanceof BABYLON.Node) {
  43638. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  43639. }
  43640. else {
  43641. var parameter = {};
  43642. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  43643. if (triggerOptions.parameter.mesh) {
  43644. parameter._meshId = triggerOptions.parameter.mesh.id;
  43645. }
  43646. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  43647. }
  43648. }
  43649. // Serialize child action, recursively
  43650. this.actions[i].serialize(triggerObject);
  43651. // Add serialized trigger
  43652. root.children.push(triggerObject);
  43653. }
  43654. return root;
  43655. };
  43656. ActionManager.Parse = function (parsedActions, object, scene) {
  43657. var actionManager = new ActionManager(scene);
  43658. if (object === null)
  43659. scene.actionManager = actionManager;
  43660. else
  43661. object.actionManager = actionManager;
  43662. // instanciate a new object
  43663. var instanciate = function (name, params) {
  43664. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  43665. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  43666. newInstance.constructor.apply(newInstance, params);
  43667. return newInstance;
  43668. };
  43669. var parseParameter = function (name, value, target, propertyPath) {
  43670. if (propertyPath === null) {
  43671. // String, boolean or float
  43672. var floatValue = parseFloat(value);
  43673. if (value === "true" || value === "false")
  43674. return value === "true";
  43675. else
  43676. return isNaN(floatValue) ? value : floatValue;
  43677. }
  43678. var effectiveTarget = propertyPath.split(".");
  43679. var values = value.split(",");
  43680. // Get effective Target
  43681. for (var i = 0; i < effectiveTarget.length; i++) {
  43682. target = target[effectiveTarget[i]];
  43683. }
  43684. // Return appropriate value with its type
  43685. if (typeof (target) === "boolean")
  43686. return values[0] === "true";
  43687. if (typeof (target) === "string")
  43688. return values[0];
  43689. // Parameters with multiple values such as Vector3 etc.
  43690. var split = new Array();
  43691. for (var i = 0; i < values.length; i++)
  43692. split.push(parseFloat(values[i]));
  43693. if (target instanceof BABYLON.Vector3)
  43694. return BABYLON.Vector3.FromArray(split);
  43695. if (target instanceof BABYLON.Vector4)
  43696. return BABYLON.Vector4.FromArray(split);
  43697. if (target instanceof BABYLON.Color3)
  43698. return BABYLON.Color3.FromArray(split);
  43699. if (target instanceof BABYLON.Color4)
  43700. return BABYLON.Color4.FromArray(split);
  43701. return parseFloat(values[0]);
  43702. };
  43703. // traverse graph per trigger
  43704. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  43705. if (combineArray === void 0) { combineArray = null; }
  43706. if (parsedAction.detached)
  43707. return;
  43708. var parameters = new Array();
  43709. var target = null;
  43710. var propertyPath = null;
  43711. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  43712. // Parameters
  43713. if (parsedAction.type === 2)
  43714. parameters.push(actionManager);
  43715. else
  43716. parameters.push(trigger);
  43717. if (combine) {
  43718. var actions = new Array();
  43719. for (var j = 0; j < parsedAction.combine.length; j++) {
  43720. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  43721. }
  43722. parameters.push(actions);
  43723. }
  43724. else {
  43725. for (var i = 0; i < parsedAction.properties.length; i++) {
  43726. var value = parsedAction.properties[i].value;
  43727. var name = parsedAction.properties[i].name;
  43728. var targetType = parsedAction.properties[i].targetType;
  43729. if (name === "target")
  43730. if (targetType !== null && targetType === "SceneProperties")
  43731. value = target = scene;
  43732. else
  43733. value = target = scene.getNodeByName(value);
  43734. else if (name === "parent")
  43735. value = scene.getNodeByName(value);
  43736. else if (name === "sound")
  43737. value = scene.getSoundByName(value);
  43738. else if (name !== "propertyPath") {
  43739. if (parsedAction.type === 2 && name === "operator")
  43740. value = BABYLON.ValueCondition[value];
  43741. else
  43742. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  43743. }
  43744. else {
  43745. propertyPath = value;
  43746. }
  43747. parameters.push(value);
  43748. }
  43749. }
  43750. if (combineArray === null) {
  43751. parameters.push(condition);
  43752. }
  43753. else {
  43754. parameters.push(null);
  43755. }
  43756. // If interpolate value action
  43757. if (parsedAction.name === "InterpolateValueAction") {
  43758. var param = parameters[parameters.length - 2];
  43759. parameters[parameters.length - 1] = param;
  43760. parameters[parameters.length - 2] = condition;
  43761. }
  43762. // Action or condition(s) and not CombineAction
  43763. var newAction = instanciate(parsedAction.name, parameters);
  43764. if (newAction instanceof BABYLON.Condition && condition !== null) {
  43765. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  43766. if (action)
  43767. action.then(nothing);
  43768. else
  43769. actionManager.registerAction(nothing);
  43770. action = nothing;
  43771. }
  43772. if (combineArray === null) {
  43773. if (newAction instanceof BABYLON.Condition) {
  43774. condition = newAction;
  43775. newAction = action;
  43776. }
  43777. else {
  43778. condition = null;
  43779. if (action)
  43780. action.then(newAction);
  43781. else
  43782. actionManager.registerAction(newAction);
  43783. }
  43784. }
  43785. else {
  43786. combineArray.push(newAction);
  43787. }
  43788. for (var i = 0; i < parsedAction.children.length; i++)
  43789. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  43790. };
  43791. // triggers
  43792. for (var i = 0; i < parsedActions.children.length; i++) {
  43793. var triggerParams;
  43794. var trigger = parsedActions.children[i];
  43795. if (trigger.properties.length > 0) {
  43796. var param = trigger.properties[0].value;
  43797. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  43798. if (value._meshId) {
  43799. value.mesh = scene.getMeshByID(value._meshId);
  43800. }
  43801. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  43802. }
  43803. else
  43804. triggerParams = ActionManager[trigger.name];
  43805. for (var j = 0; j < trigger.children.length; j++) {
  43806. if (!trigger.detached)
  43807. traverse(trigger.children[j], triggerParams, null, null);
  43808. }
  43809. }
  43810. };
  43811. ActionManager.GetTriggerName = function (trigger) {
  43812. switch (trigger) {
  43813. case 0: return "NothingTrigger";
  43814. case 1: return "OnPickTrigger";
  43815. case 2: return "OnLeftPickTrigger";
  43816. case 3: return "OnRightPickTrigger";
  43817. case 4: return "OnCenterPickTrigger";
  43818. case 5: return "OnPickDownTrigger";
  43819. case 6: return "OnPickUpTrigger";
  43820. case 7: return "OnLongPressTrigger";
  43821. case 8: return "OnPointerOverTrigger";
  43822. case 9: return "OnPointerOutTrigger";
  43823. case 10: return "OnEveryFrameTrigger";
  43824. case 11: return "OnIntersectionEnterTrigger";
  43825. case 12: return "OnIntersectionExitTrigger";
  43826. case 13: return "OnKeyDownTrigger";
  43827. case 14: return "OnKeyUpTrigger";
  43828. case 15: return "OnPickOutTrigger";
  43829. default: return "";
  43830. }
  43831. };
  43832. // Statics
  43833. ActionManager._NothingTrigger = 0;
  43834. ActionManager._OnPickTrigger = 1;
  43835. ActionManager._OnLeftPickTrigger = 2;
  43836. ActionManager._OnRightPickTrigger = 3;
  43837. ActionManager._OnCenterPickTrigger = 4;
  43838. ActionManager._OnPickDownTrigger = 5;
  43839. ActionManager._OnDoublePickTrigger = 6;
  43840. ActionManager._OnPickUpTrigger = 7;
  43841. ActionManager._OnLongPressTrigger = 8;
  43842. ActionManager._OnPointerOverTrigger = 9;
  43843. ActionManager._OnPointerOutTrigger = 10;
  43844. ActionManager._OnEveryFrameTrigger = 11;
  43845. ActionManager._OnIntersectionEnterTrigger = 12;
  43846. ActionManager._OnIntersectionExitTrigger = 13;
  43847. ActionManager._OnKeyDownTrigger = 14;
  43848. ActionManager._OnKeyUpTrigger = 15;
  43849. ActionManager._OnPickOutTrigger = 16;
  43850. ActionManager.Triggers = {};
  43851. return ActionManager;
  43852. }());
  43853. BABYLON.ActionManager = ActionManager;
  43854. })(BABYLON || (BABYLON = {}));
  43855. //# sourceMappingURL=babylon.actionManager.js.map
  43856. var BABYLON;
  43857. (function (BABYLON) {
  43858. var InterpolateValueAction = /** @class */ (function (_super) {
  43859. __extends(InterpolateValueAction, _super);
  43860. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  43861. if (duration === void 0) { duration = 1000; }
  43862. var _this = _super.call(this, triggerOptions, condition) || this;
  43863. _this.propertyPath = propertyPath;
  43864. _this.value = value;
  43865. _this.duration = duration;
  43866. _this.stopOtherAnimations = stopOtherAnimations;
  43867. _this.onInterpolationDone = onInterpolationDone;
  43868. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  43869. _this._target = _this._effectiveTarget = target;
  43870. return _this;
  43871. }
  43872. InterpolateValueAction.prototype._prepare = function () {
  43873. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  43874. this._property = this._getProperty(this.propertyPath);
  43875. };
  43876. InterpolateValueAction.prototype.execute = function () {
  43877. var _this = this;
  43878. var scene = this._actionManager.getScene();
  43879. var keys = [
  43880. {
  43881. frame: 0,
  43882. value: this._effectiveTarget[this._property]
  43883. }, {
  43884. frame: 100,
  43885. value: this.value
  43886. }
  43887. ];
  43888. var dataType;
  43889. if (typeof this.value === "number") {
  43890. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  43891. }
  43892. else if (this.value instanceof BABYLON.Color3) {
  43893. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  43894. }
  43895. else if (this.value instanceof BABYLON.Vector3) {
  43896. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  43897. }
  43898. else if (this.value instanceof BABYLON.Matrix) {
  43899. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  43900. }
  43901. else if (this.value instanceof BABYLON.Quaternion) {
  43902. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  43903. }
  43904. else {
  43905. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  43906. return;
  43907. }
  43908. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  43909. animation.setKeys(keys);
  43910. if (this.stopOtherAnimations) {
  43911. scene.stopAnimation(this._effectiveTarget);
  43912. }
  43913. var wrapper = function () {
  43914. _this.onInterpolationDoneObservable.notifyObservers(_this);
  43915. if (_this.onInterpolationDone) {
  43916. _this.onInterpolationDone();
  43917. }
  43918. };
  43919. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  43920. };
  43921. InterpolateValueAction.prototype.serialize = function (parent) {
  43922. return _super.prototype._serialize.call(this, {
  43923. name: "InterpolateValueAction",
  43924. properties: [
  43925. BABYLON.Action._GetTargetProperty(this._target),
  43926. { name: "propertyPath", value: this.propertyPath },
  43927. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  43928. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  43929. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  43930. ]
  43931. }, parent);
  43932. };
  43933. return InterpolateValueAction;
  43934. }(BABYLON.Action));
  43935. BABYLON.InterpolateValueAction = InterpolateValueAction;
  43936. })(BABYLON || (BABYLON = {}));
  43937. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  43938. var BABYLON;
  43939. (function (BABYLON) {
  43940. var SwitchBooleanAction = /** @class */ (function (_super) {
  43941. __extends(SwitchBooleanAction, _super);
  43942. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  43943. var _this = _super.call(this, triggerOptions, condition) || this;
  43944. _this.propertyPath = propertyPath;
  43945. _this._target = _this._effectiveTarget = target;
  43946. return _this;
  43947. }
  43948. SwitchBooleanAction.prototype._prepare = function () {
  43949. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  43950. this._property = this._getProperty(this.propertyPath);
  43951. };
  43952. SwitchBooleanAction.prototype.execute = function () {
  43953. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  43954. };
  43955. SwitchBooleanAction.prototype.serialize = function (parent) {
  43956. return _super.prototype._serialize.call(this, {
  43957. name: "SwitchBooleanAction",
  43958. properties: [
  43959. BABYLON.Action._GetTargetProperty(this._target),
  43960. { name: "propertyPath", value: this.propertyPath }
  43961. ]
  43962. }, parent);
  43963. };
  43964. return SwitchBooleanAction;
  43965. }(BABYLON.Action));
  43966. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  43967. var SetStateAction = /** @class */ (function (_super) {
  43968. __extends(SetStateAction, _super);
  43969. function SetStateAction(triggerOptions, target, value, condition) {
  43970. var _this = _super.call(this, triggerOptions, condition) || this;
  43971. _this.value = value;
  43972. _this._target = target;
  43973. return _this;
  43974. }
  43975. SetStateAction.prototype.execute = function () {
  43976. this._target.state = this.value;
  43977. };
  43978. SetStateAction.prototype.serialize = function (parent) {
  43979. return _super.prototype._serialize.call(this, {
  43980. name: "SetStateAction",
  43981. properties: [
  43982. BABYLON.Action._GetTargetProperty(this._target),
  43983. { name: "value", value: this.value }
  43984. ]
  43985. }, parent);
  43986. };
  43987. return SetStateAction;
  43988. }(BABYLON.Action));
  43989. BABYLON.SetStateAction = SetStateAction;
  43990. var SetValueAction = /** @class */ (function (_super) {
  43991. __extends(SetValueAction, _super);
  43992. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  43993. var _this = _super.call(this, triggerOptions, condition) || this;
  43994. _this.propertyPath = propertyPath;
  43995. _this.value = value;
  43996. _this._target = _this._effectiveTarget = target;
  43997. return _this;
  43998. }
  43999. SetValueAction.prototype._prepare = function () {
  44000. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  44001. this._property = this._getProperty(this.propertyPath);
  44002. };
  44003. SetValueAction.prototype.execute = function () {
  44004. this._effectiveTarget[this._property] = this.value;
  44005. if (this._target.markAsDirty) {
  44006. this._target.markAsDirty(this._property);
  44007. }
  44008. };
  44009. SetValueAction.prototype.serialize = function (parent) {
  44010. return _super.prototype._serialize.call(this, {
  44011. name: "SetValueAction",
  44012. properties: [
  44013. BABYLON.Action._GetTargetProperty(this._target),
  44014. { name: "propertyPath", value: this.propertyPath },
  44015. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  44016. ]
  44017. }, parent);
  44018. };
  44019. return SetValueAction;
  44020. }(BABYLON.Action));
  44021. BABYLON.SetValueAction = SetValueAction;
  44022. var IncrementValueAction = /** @class */ (function (_super) {
  44023. __extends(IncrementValueAction, _super);
  44024. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  44025. var _this = _super.call(this, triggerOptions, condition) || this;
  44026. _this.propertyPath = propertyPath;
  44027. _this.value = value;
  44028. _this._target = _this._effectiveTarget = target;
  44029. return _this;
  44030. }
  44031. IncrementValueAction.prototype._prepare = function () {
  44032. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  44033. this._property = this._getProperty(this.propertyPath);
  44034. if (typeof this._effectiveTarget[this._property] !== "number") {
  44035. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  44036. }
  44037. };
  44038. IncrementValueAction.prototype.execute = function () {
  44039. this._effectiveTarget[this._property] += this.value;
  44040. if (this._target.markAsDirty) {
  44041. this._target.markAsDirty(this._property);
  44042. }
  44043. };
  44044. IncrementValueAction.prototype.serialize = function (parent) {
  44045. return _super.prototype._serialize.call(this, {
  44046. name: "IncrementValueAction",
  44047. properties: [
  44048. BABYLON.Action._GetTargetProperty(this._target),
  44049. { name: "propertyPath", value: this.propertyPath },
  44050. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  44051. ]
  44052. }, parent);
  44053. };
  44054. return IncrementValueAction;
  44055. }(BABYLON.Action));
  44056. BABYLON.IncrementValueAction = IncrementValueAction;
  44057. var PlayAnimationAction = /** @class */ (function (_super) {
  44058. __extends(PlayAnimationAction, _super);
  44059. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  44060. var _this = _super.call(this, triggerOptions, condition) || this;
  44061. _this.from = from;
  44062. _this.to = to;
  44063. _this.loop = loop;
  44064. _this._target = target;
  44065. return _this;
  44066. }
  44067. PlayAnimationAction.prototype._prepare = function () {
  44068. };
  44069. PlayAnimationAction.prototype.execute = function () {
  44070. var scene = this._actionManager.getScene();
  44071. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  44072. };
  44073. PlayAnimationAction.prototype.serialize = function (parent) {
  44074. return _super.prototype._serialize.call(this, {
  44075. name: "PlayAnimationAction",
  44076. properties: [
  44077. BABYLON.Action._GetTargetProperty(this._target),
  44078. { name: "from", value: String(this.from) },
  44079. { name: "to", value: String(this.to) },
  44080. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  44081. ]
  44082. }, parent);
  44083. };
  44084. return PlayAnimationAction;
  44085. }(BABYLON.Action));
  44086. BABYLON.PlayAnimationAction = PlayAnimationAction;
  44087. var StopAnimationAction = /** @class */ (function (_super) {
  44088. __extends(StopAnimationAction, _super);
  44089. function StopAnimationAction(triggerOptions, target, condition) {
  44090. var _this = _super.call(this, triggerOptions, condition) || this;
  44091. _this._target = target;
  44092. return _this;
  44093. }
  44094. StopAnimationAction.prototype._prepare = function () {
  44095. };
  44096. StopAnimationAction.prototype.execute = function () {
  44097. var scene = this._actionManager.getScene();
  44098. scene.stopAnimation(this._target);
  44099. };
  44100. StopAnimationAction.prototype.serialize = function (parent) {
  44101. return _super.prototype._serialize.call(this, {
  44102. name: "StopAnimationAction",
  44103. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  44104. }, parent);
  44105. };
  44106. return StopAnimationAction;
  44107. }(BABYLON.Action));
  44108. BABYLON.StopAnimationAction = StopAnimationAction;
  44109. var DoNothingAction = /** @class */ (function (_super) {
  44110. __extends(DoNothingAction, _super);
  44111. function DoNothingAction(triggerOptions, condition) {
  44112. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  44113. return _super.call(this, triggerOptions, condition) || this;
  44114. }
  44115. DoNothingAction.prototype.execute = function () {
  44116. };
  44117. DoNothingAction.prototype.serialize = function (parent) {
  44118. return _super.prototype._serialize.call(this, {
  44119. name: "DoNothingAction",
  44120. properties: []
  44121. }, parent);
  44122. };
  44123. return DoNothingAction;
  44124. }(BABYLON.Action));
  44125. BABYLON.DoNothingAction = DoNothingAction;
  44126. var CombineAction = /** @class */ (function (_super) {
  44127. __extends(CombineAction, _super);
  44128. function CombineAction(triggerOptions, children, condition) {
  44129. var _this = _super.call(this, triggerOptions, condition) || this;
  44130. _this.children = children;
  44131. return _this;
  44132. }
  44133. CombineAction.prototype._prepare = function () {
  44134. for (var index = 0; index < this.children.length; index++) {
  44135. this.children[index]._actionManager = this._actionManager;
  44136. this.children[index]._prepare();
  44137. }
  44138. };
  44139. CombineAction.prototype.execute = function (evt) {
  44140. for (var index = 0; index < this.children.length; index++) {
  44141. this.children[index].execute(evt);
  44142. }
  44143. };
  44144. CombineAction.prototype.serialize = function (parent) {
  44145. var serializationObject = _super.prototype._serialize.call(this, {
  44146. name: "CombineAction",
  44147. properties: [],
  44148. combine: []
  44149. }, parent);
  44150. for (var i = 0; i < this.children.length; i++) {
  44151. serializationObject.combine.push(this.children[i].serialize(null));
  44152. }
  44153. return serializationObject;
  44154. };
  44155. return CombineAction;
  44156. }(BABYLON.Action));
  44157. BABYLON.CombineAction = CombineAction;
  44158. var ExecuteCodeAction = /** @class */ (function (_super) {
  44159. __extends(ExecuteCodeAction, _super);
  44160. function ExecuteCodeAction(triggerOptions, func, condition) {
  44161. var _this = _super.call(this, triggerOptions, condition) || this;
  44162. _this.func = func;
  44163. return _this;
  44164. }
  44165. ExecuteCodeAction.prototype.execute = function (evt) {
  44166. this.func(evt);
  44167. };
  44168. return ExecuteCodeAction;
  44169. }(BABYLON.Action));
  44170. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  44171. var SetParentAction = /** @class */ (function (_super) {
  44172. __extends(SetParentAction, _super);
  44173. function SetParentAction(triggerOptions, target, parent, condition) {
  44174. var _this = _super.call(this, triggerOptions, condition) || this;
  44175. _this._target = target;
  44176. _this._parent = parent;
  44177. return _this;
  44178. }
  44179. SetParentAction.prototype._prepare = function () {
  44180. };
  44181. SetParentAction.prototype.execute = function () {
  44182. if (this._target.parent === this._parent) {
  44183. return;
  44184. }
  44185. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  44186. invertParentWorldMatrix.invert();
  44187. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  44188. this._target.parent = this._parent;
  44189. };
  44190. SetParentAction.prototype.serialize = function (parent) {
  44191. return _super.prototype._serialize.call(this, {
  44192. name: "SetParentAction",
  44193. properties: [
  44194. BABYLON.Action._GetTargetProperty(this._target),
  44195. BABYLON.Action._GetTargetProperty(this._parent),
  44196. ]
  44197. }, parent);
  44198. };
  44199. return SetParentAction;
  44200. }(BABYLON.Action));
  44201. BABYLON.SetParentAction = SetParentAction;
  44202. var PlaySoundAction = /** @class */ (function (_super) {
  44203. __extends(PlaySoundAction, _super);
  44204. function PlaySoundAction(triggerOptions, sound, condition) {
  44205. var _this = _super.call(this, triggerOptions, condition) || this;
  44206. _this._sound = sound;
  44207. return _this;
  44208. }
  44209. PlaySoundAction.prototype._prepare = function () {
  44210. };
  44211. PlaySoundAction.prototype.execute = function () {
  44212. if (this._sound !== undefined)
  44213. this._sound.play();
  44214. };
  44215. PlaySoundAction.prototype.serialize = function (parent) {
  44216. return _super.prototype._serialize.call(this, {
  44217. name: "PlaySoundAction",
  44218. properties: [{ name: "sound", value: this._sound.name }]
  44219. }, parent);
  44220. };
  44221. return PlaySoundAction;
  44222. }(BABYLON.Action));
  44223. BABYLON.PlaySoundAction = PlaySoundAction;
  44224. var StopSoundAction = /** @class */ (function (_super) {
  44225. __extends(StopSoundAction, _super);
  44226. function StopSoundAction(triggerOptions, sound, condition) {
  44227. var _this = _super.call(this, triggerOptions, condition) || this;
  44228. _this._sound = sound;
  44229. return _this;
  44230. }
  44231. StopSoundAction.prototype._prepare = function () {
  44232. };
  44233. StopSoundAction.prototype.execute = function () {
  44234. if (this._sound !== undefined)
  44235. this._sound.stop();
  44236. };
  44237. StopSoundAction.prototype.serialize = function (parent) {
  44238. return _super.prototype._serialize.call(this, {
  44239. name: "StopSoundAction",
  44240. properties: [{ name: "sound", value: this._sound.name }]
  44241. }, parent);
  44242. };
  44243. return StopSoundAction;
  44244. }(BABYLON.Action));
  44245. BABYLON.StopSoundAction = StopSoundAction;
  44246. })(BABYLON || (BABYLON = {}));
  44247. //# sourceMappingURL=babylon.directActions.js.map
  44248. var BABYLON;
  44249. (function (BABYLON) {
  44250. var SpriteManager = /** @class */ (function () {
  44251. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  44252. if (epsilon === void 0) { epsilon = 0.01; }
  44253. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  44254. this.name = name;
  44255. this.sprites = new Array();
  44256. this.renderingGroupId = 0;
  44257. this.layerMask = 0x0FFFFFFF;
  44258. this.fogEnabled = true;
  44259. this.isPickable = false;
  44260. /**
  44261. * An event triggered when the manager is disposed.
  44262. * @type {BABYLON.Observable}
  44263. */
  44264. this.onDisposeObservable = new BABYLON.Observable();
  44265. this._vertexBuffers = {};
  44266. this._capacity = capacity;
  44267. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  44268. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  44269. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  44270. if (cellSize.width && cellSize.height) {
  44271. this.cellWidth = cellSize.width;
  44272. this.cellHeight = cellSize.height;
  44273. }
  44274. else if (cellSize !== undefined) {
  44275. this.cellWidth = cellSize;
  44276. this.cellHeight = cellSize;
  44277. }
  44278. else {
  44279. return;
  44280. }
  44281. this._epsilon = epsilon;
  44282. this._scene = scene;
  44283. this._scene.spriteManagers.push(this);
  44284. var indices = [];
  44285. var index = 0;
  44286. for (var count = 0; count < capacity; count++) {
  44287. indices.push(index);
  44288. indices.push(index + 1);
  44289. indices.push(index + 2);
  44290. indices.push(index);
  44291. indices.push(index + 2);
  44292. indices.push(index + 3);
  44293. index += 4;
  44294. }
  44295. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  44296. // VBO
  44297. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  44298. this._vertexData = new Float32Array(capacity * 16 * 4);
  44299. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  44300. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  44301. var options = this._buffer.createVertexBuffer("options", 4, 4);
  44302. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  44303. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  44304. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  44305. this._vertexBuffers["options"] = options;
  44306. this._vertexBuffers["cellInfo"] = cellInfo;
  44307. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  44308. // Effects
  44309. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  44310. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  44311. }
  44312. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  44313. set: function (callback) {
  44314. if (this._onDisposeObserver) {
  44315. this.onDisposeObservable.remove(this._onDisposeObserver);
  44316. }
  44317. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  44318. },
  44319. enumerable: true,
  44320. configurable: true
  44321. });
  44322. Object.defineProperty(SpriteManager.prototype, "texture", {
  44323. get: function () {
  44324. return this._spriteTexture;
  44325. },
  44326. set: function (value) {
  44327. this._spriteTexture = value;
  44328. },
  44329. enumerable: true,
  44330. configurable: true
  44331. });
  44332. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  44333. var arrayOffset = index * 16;
  44334. if (offsetX === 0)
  44335. offsetX = this._epsilon;
  44336. else if (offsetX === 1)
  44337. offsetX = 1 - this._epsilon;
  44338. if (offsetY === 0)
  44339. offsetY = this._epsilon;
  44340. else if (offsetY === 1)
  44341. offsetY = 1 - this._epsilon;
  44342. this._vertexData[arrayOffset] = sprite.position.x;
  44343. this._vertexData[arrayOffset + 1] = sprite.position.y;
  44344. this._vertexData[arrayOffset + 2] = sprite.position.z;
  44345. this._vertexData[arrayOffset + 3] = sprite.angle;
  44346. this._vertexData[arrayOffset + 4] = sprite.width;
  44347. this._vertexData[arrayOffset + 5] = sprite.height;
  44348. this._vertexData[arrayOffset + 6] = offsetX;
  44349. this._vertexData[arrayOffset + 7] = offsetY;
  44350. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  44351. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  44352. var offset = (sprite.cellIndex / rowSize) >> 0;
  44353. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  44354. this._vertexData[arrayOffset + 11] = offset;
  44355. // Color
  44356. this._vertexData[arrayOffset + 12] = sprite.color.r;
  44357. this._vertexData[arrayOffset + 13] = sprite.color.g;
  44358. this._vertexData[arrayOffset + 14] = sprite.color.b;
  44359. this._vertexData[arrayOffset + 15] = sprite.color.a;
  44360. };
  44361. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  44362. var count = Math.min(this._capacity, this.sprites.length);
  44363. var min = BABYLON.Vector3.Zero();
  44364. var max = BABYLON.Vector3.Zero();
  44365. var distance = Number.MAX_VALUE;
  44366. var currentSprite = null;
  44367. var cameraSpacePosition = BABYLON.Vector3.Zero();
  44368. var cameraView = camera.getViewMatrix();
  44369. for (var index = 0; index < count; index++) {
  44370. var sprite = this.sprites[index];
  44371. if (!sprite) {
  44372. continue;
  44373. }
  44374. if (predicate) {
  44375. if (!predicate(sprite)) {
  44376. continue;
  44377. }
  44378. }
  44379. else if (!sprite.isPickable) {
  44380. continue;
  44381. }
  44382. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  44383. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  44384. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  44385. if (ray.intersectsBoxMinMax(min, max)) {
  44386. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  44387. if (distance > currentDistance) {
  44388. distance = currentDistance;
  44389. currentSprite = sprite;
  44390. if (fastCheck) {
  44391. break;
  44392. }
  44393. }
  44394. }
  44395. }
  44396. if (currentSprite) {
  44397. var result = new BABYLON.PickingInfo();
  44398. result.hit = true;
  44399. result.pickedSprite = currentSprite;
  44400. result.distance = distance;
  44401. return result;
  44402. }
  44403. return null;
  44404. };
  44405. SpriteManager.prototype.render = function () {
  44406. // Check
  44407. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  44408. return;
  44409. var engine = this._scene.getEngine();
  44410. var baseSize = this._spriteTexture.getBaseSize();
  44411. // Sprites
  44412. var deltaTime = engine.getDeltaTime();
  44413. var max = Math.min(this._capacity, this.sprites.length);
  44414. var rowSize = baseSize.width / this.cellWidth;
  44415. var offset = 0;
  44416. for (var index = 0; index < max; index++) {
  44417. var sprite = this.sprites[index];
  44418. if (!sprite) {
  44419. continue;
  44420. }
  44421. sprite._animate(deltaTime);
  44422. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  44423. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  44424. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  44425. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  44426. }
  44427. this._buffer.update(this._vertexData);
  44428. // Render
  44429. var effect = this._effectBase;
  44430. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  44431. effect = this._effectFog;
  44432. }
  44433. engine.enableEffect(effect);
  44434. var viewMatrix = this._scene.getViewMatrix();
  44435. effect.setTexture("diffuseSampler", this._spriteTexture);
  44436. effect.setMatrix("view", viewMatrix);
  44437. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  44438. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  44439. // Fog
  44440. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  44441. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  44442. effect.setColor3("vFogColor", this._scene.fogColor);
  44443. }
  44444. // VBOs
  44445. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  44446. // Draw order
  44447. engine.setDepthFunctionToLessOrEqual();
  44448. effect.setBool("alphaTest", true);
  44449. engine.setColorWrite(false);
  44450. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  44451. engine.setColorWrite(true);
  44452. effect.setBool("alphaTest", false);
  44453. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  44454. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  44455. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  44456. };
  44457. SpriteManager.prototype.dispose = function () {
  44458. if (this._buffer) {
  44459. this._buffer.dispose();
  44460. this._buffer = null;
  44461. }
  44462. if (this._indexBuffer) {
  44463. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  44464. this._indexBuffer = null;
  44465. }
  44466. if (this._spriteTexture) {
  44467. this._spriteTexture.dispose();
  44468. this._spriteTexture = null;
  44469. }
  44470. // Remove from scene
  44471. var index = this._scene.spriteManagers.indexOf(this);
  44472. this._scene.spriteManagers.splice(index, 1);
  44473. // Callback
  44474. this.onDisposeObservable.notifyObservers(this);
  44475. this.onDisposeObservable.clear();
  44476. };
  44477. return SpriteManager;
  44478. }());
  44479. BABYLON.SpriteManager = SpriteManager;
  44480. })(BABYLON || (BABYLON = {}));
  44481. //# sourceMappingURL=babylon.spriteManager.js.map
  44482. var BABYLON;
  44483. (function (BABYLON) {
  44484. var Sprite = /** @class */ (function () {
  44485. function Sprite(name, manager) {
  44486. this.name = name;
  44487. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  44488. this.width = 1.0;
  44489. this.height = 1.0;
  44490. this.angle = 0;
  44491. this.cellIndex = 0;
  44492. this.invertU = 0;
  44493. this.invertV = 0;
  44494. this.animations = new Array();
  44495. this.isPickable = false;
  44496. this._animationStarted = false;
  44497. this._loopAnimation = false;
  44498. this._fromIndex = 0;
  44499. this._toIndex = 0;
  44500. this._delay = 0;
  44501. this._direction = 1;
  44502. this._time = 0;
  44503. this._manager = manager;
  44504. this._manager.sprites.push(this);
  44505. this.position = BABYLON.Vector3.Zero();
  44506. }
  44507. Object.defineProperty(Sprite.prototype, "size", {
  44508. get: function () {
  44509. return this.width;
  44510. },
  44511. set: function (value) {
  44512. this.width = value;
  44513. this.height = value;
  44514. },
  44515. enumerable: true,
  44516. configurable: true
  44517. });
  44518. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  44519. this._fromIndex = from;
  44520. this._toIndex = to;
  44521. this._loopAnimation = loop;
  44522. this._delay = delay;
  44523. this._animationStarted = true;
  44524. this._direction = from < to ? 1 : -1;
  44525. this.cellIndex = from;
  44526. this._time = 0;
  44527. this._onAnimationEnd = onAnimationEnd;
  44528. };
  44529. Sprite.prototype.stopAnimation = function () {
  44530. this._animationStarted = false;
  44531. };
  44532. Sprite.prototype._animate = function (deltaTime) {
  44533. if (!this._animationStarted)
  44534. return;
  44535. this._time += deltaTime;
  44536. if (this._time > this._delay) {
  44537. this._time = this._time % this._delay;
  44538. this.cellIndex += this._direction;
  44539. if (this.cellIndex > this._toIndex) {
  44540. if (this._loopAnimation) {
  44541. this.cellIndex = this._fromIndex;
  44542. }
  44543. else {
  44544. this.cellIndex = this._toIndex;
  44545. this._animationStarted = false;
  44546. if (this._onAnimationEnd) {
  44547. this._onAnimationEnd();
  44548. }
  44549. if (this.disposeWhenFinishedAnimating) {
  44550. this.dispose();
  44551. }
  44552. }
  44553. }
  44554. }
  44555. };
  44556. Sprite.prototype.dispose = function () {
  44557. for (var i = 0; i < this._manager.sprites.length; i++) {
  44558. if (this._manager.sprites[i] == this) {
  44559. this._manager.sprites.splice(i, 1);
  44560. }
  44561. }
  44562. };
  44563. return Sprite;
  44564. }());
  44565. BABYLON.Sprite = Sprite;
  44566. })(BABYLON || (BABYLON = {}));
  44567. //# sourceMappingURL=babylon.sprite.js.map
  44568. var BABYLON;
  44569. (function (BABYLON) {
  44570. var IntersectionInfo = /** @class */ (function () {
  44571. function IntersectionInfo(bu, bv, distance) {
  44572. this.bu = bu;
  44573. this.bv = bv;
  44574. this.distance = distance;
  44575. this.faceId = 0;
  44576. this.subMeshId = 0;
  44577. }
  44578. return IntersectionInfo;
  44579. }());
  44580. BABYLON.IntersectionInfo = IntersectionInfo;
  44581. var PickingInfo = /** @class */ (function () {
  44582. function PickingInfo() {
  44583. this.hit = false;
  44584. this.distance = 0;
  44585. this.pickedPoint = null;
  44586. this.pickedMesh = null;
  44587. this.bu = 0;
  44588. this.bv = 0;
  44589. this.faceId = -1;
  44590. this.subMeshId = 0;
  44591. this.pickedSprite = null;
  44592. }
  44593. // Methods
  44594. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  44595. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  44596. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  44597. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  44598. return null;
  44599. }
  44600. var indices = this.pickedMesh.getIndices();
  44601. if (!indices) {
  44602. return null;
  44603. }
  44604. var result;
  44605. if (useVerticesNormals) {
  44606. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  44607. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  44608. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  44609. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  44610. normal0 = normal0.scale(this.bu);
  44611. normal1 = normal1.scale(this.bv);
  44612. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  44613. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  44614. }
  44615. else {
  44616. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  44617. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  44618. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  44619. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  44620. var p1p2 = vertex1.subtract(vertex2);
  44621. var p3p2 = vertex3.subtract(vertex2);
  44622. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  44623. }
  44624. if (useWorldCoordinates) {
  44625. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  44626. }
  44627. return BABYLON.Vector3.Normalize(result);
  44628. };
  44629. PickingInfo.prototype.getTextureCoordinates = function () {
  44630. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  44631. return null;
  44632. }
  44633. var indices = this.pickedMesh.getIndices();
  44634. if (!indices) {
  44635. return null;
  44636. }
  44637. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  44638. if (!uvs) {
  44639. return null;
  44640. }
  44641. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  44642. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  44643. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  44644. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  44645. uv1 = uv1.scale(this.bu);
  44646. uv2 = uv2.scale(this.bv);
  44647. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  44648. };
  44649. return PickingInfo;
  44650. }());
  44651. BABYLON.PickingInfo = PickingInfo;
  44652. })(BABYLON || (BABYLON = {}));
  44653. //# sourceMappingURL=babylon.pickingInfo.js.map
  44654. var BABYLON;
  44655. (function (BABYLON) {
  44656. var Ray = /** @class */ (function () {
  44657. function Ray(origin, direction, length) {
  44658. if (length === void 0) { length = Number.MAX_VALUE; }
  44659. this.origin = origin;
  44660. this.direction = direction;
  44661. this.length = length;
  44662. }
  44663. // Methods
  44664. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  44665. var d = 0.0;
  44666. var maxValue = Number.MAX_VALUE;
  44667. var inv;
  44668. var min;
  44669. var max;
  44670. var temp;
  44671. if (Math.abs(this.direction.x) < 0.0000001) {
  44672. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  44673. return false;
  44674. }
  44675. }
  44676. else {
  44677. inv = 1.0 / this.direction.x;
  44678. min = (minimum.x - this.origin.x) * inv;
  44679. max = (maximum.x - this.origin.x) * inv;
  44680. if (max === -Infinity) {
  44681. max = Infinity;
  44682. }
  44683. if (min > max) {
  44684. temp = min;
  44685. min = max;
  44686. max = temp;
  44687. }
  44688. d = Math.max(min, d);
  44689. maxValue = Math.min(max, maxValue);
  44690. if (d > maxValue) {
  44691. return false;
  44692. }
  44693. }
  44694. if (Math.abs(this.direction.y) < 0.0000001) {
  44695. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  44696. return false;
  44697. }
  44698. }
  44699. else {
  44700. inv = 1.0 / this.direction.y;
  44701. min = (minimum.y - this.origin.y) * inv;
  44702. max = (maximum.y - this.origin.y) * inv;
  44703. if (max === -Infinity) {
  44704. max = Infinity;
  44705. }
  44706. if (min > max) {
  44707. temp = min;
  44708. min = max;
  44709. max = temp;
  44710. }
  44711. d = Math.max(min, d);
  44712. maxValue = Math.min(max, maxValue);
  44713. if (d > maxValue) {
  44714. return false;
  44715. }
  44716. }
  44717. if (Math.abs(this.direction.z) < 0.0000001) {
  44718. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  44719. return false;
  44720. }
  44721. }
  44722. else {
  44723. inv = 1.0 / this.direction.z;
  44724. min = (minimum.z - this.origin.z) * inv;
  44725. max = (maximum.z - this.origin.z) * inv;
  44726. if (max === -Infinity) {
  44727. max = Infinity;
  44728. }
  44729. if (min > max) {
  44730. temp = min;
  44731. min = max;
  44732. max = temp;
  44733. }
  44734. d = Math.max(min, d);
  44735. maxValue = Math.min(max, maxValue);
  44736. if (d > maxValue) {
  44737. return false;
  44738. }
  44739. }
  44740. return true;
  44741. };
  44742. Ray.prototype.intersectsBox = function (box) {
  44743. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  44744. };
  44745. Ray.prototype.intersectsSphere = function (sphere) {
  44746. var x = sphere.center.x - this.origin.x;
  44747. var y = sphere.center.y - this.origin.y;
  44748. var z = sphere.center.z - this.origin.z;
  44749. var pyth = (x * x) + (y * y) + (z * z);
  44750. var rr = sphere.radius * sphere.radius;
  44751. if (pyth <= rr) {
  44752. return true;
  44753. }
  44754. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  44755. if (dot < 0.0) {
  44756. return false;
  44757. }
  44758. var temp = pyth - (dot * dot);
  44759. return temp <= rr;
  44760. };
  44761. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  44762. if (!this._edge1) {
  44763. this._edge1 = BABYLON.Vector3.Zero();
  44764. this._edge2 = BABYLON.Vector3.Zero();
  44765. this._pvec = BABYLON.Vector3.Zero();
  44766. this._tvec = BABYLON.Vector3.Zero();
  44767. this._qvec = BABYLON.Vector3.Zero();
  44768. }
  44769. vertex1.subtractToRef(vertex0, this._edge1);
  44770. vertex2.subtractToRef(vertex0, this._edge2);
  44771. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  44772. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  44773. if (det === 0) {
  44774. return null;
  44775. }
  44776. var invdet = 1 / det;
  44777. this.origin.subtractToRef(vertex0, this._tvec);
  44778. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  44779. if (bu < 0 || bu > 1.0) {
  44780. return null;
  44781. }
  44782. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  44783. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  44784. if (bv < 0 || bu + bv > 1.0) {
  44785. return null;
  44786. }
  44787. //check if the distance is longer than the predefined length.
  44788. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  44789. if (distance > this.length) {
  44790. return null;
  44791. }
  44792. return new BABYLON.IntersectionInfo(bu, bv, distance);
  44793. };
  44794. Ray.prototype.intersectsPlane = function (plane) {
  44795. var distance;
  44796. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  44797. if (Math.abs(result1) < 9.99999997475243E-07) {
  44798. return null;
  44799. }
  44800. else {
  44801. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  44802. distance = (-plane.d - result2) / result1;
  44803. if (distance < 0.0) {
  44804. if (distance < -9.99999997475243E-07) {
  44805. return null;
  44806. }
  44807. else {
  44808. return 0;
  44809. }
  44810. }
  44811. return distance;
  44812. }
  44813. };
  44814. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  44815. var tm = BABYLON.Tmp.Matrix[0];
  44816. mesh.getWorldMatrix().invertToRef(tm);
  44817. if (this._tmpRay) {
  44818. Ray.TransformToRef(this, tm, this._tmpRay);
  44819. }
  44820. else {
  44821. this._tmpRay = Ray.Transform(this, tm);
  44822. }
  44823. return mesh.intersects(this._tmpRay, fastCheck);
  44824. };
  44825. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  44826. if (results) {
  44827. results.length = 0;
  44828. }
  44829. else {
  44830. results = [];
  44831. }
  44832. for (var i = 0; i < meshes.length; i++) {
  44833. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  44834. if (pickInfo.hit) {
  44835. results.push(pickInfo);
  44836. }
  44837. }
  44838. results.sort(this._comparePickingInfo);
  44839. return results;
  44840. };
  44841. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  44842. if (pickingInfoA.distance < pickingInfoB.distance) {
  44843. return -1;
  44844. }
  44845. else if (pickingInfoA.distance > pickingInfoB.distance) {
  44846. return 1;
  44847. }
  44848. else {
  44849. return 0;
  44850. }
  44851. };
  44852. /**
  44853. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  44854. * @param sega the first point of the segment to test the intersection against
  44855. * @param segb the second point of the segment to test the intersection against
  44856. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  44857. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  44858. */
  44859. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  44860. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  44861. var u = segb.subtract(sega);
  44862. var v = rsegb.subtract(this.origin);
  44863. var w = sega.subtract(this.origin);
  44864. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  44865. var b = BABYLON.Vector3.Dot(u, v);
  44866. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  44867. var d = BABYLON.Vector3.Dot(u, w);
  44868. var e = BABYLON.Vector3.Dot(v, w);
  44869. var D = a * c - b * b; // always >= 0
  44870. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  44871. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  44872. // compute the line parameters of the two closest points
  44873. if (D < Ray.smallnum) {
  44874. sN = 0.0; // force using point P0 on segment S1
  44875. sD = 1.0; // to prevent possible division by 0.0 later
  44876. tN = e;
  44877. tD = c;
  44878. }
  44879. else {
  44880. sN = (b * e - c * d);
  44881. tN = (a * e - b * d);
  44882. if (sN < 0.0) {
  44883. sN = 0.0;
  44884. tN = e;
  44885. tD = c;
  44886. }
  44887. else if (sN > sD) {
  44888. sN = sD;
  44889. tN = e + b;
  44890. tD = c;
  44891. }
  44892. }
  44893. if (tN < 0.0) {
  44894. tN = 0.0;
  44895. // recompute sc for this edge
  44896. if (-d < 0.0) {
  44897. sN = 0.0;
  44898. }
  44899. else if (-d > a)
  44900. sN = sD;
  44901. else {
  44902. sN = -d;
  44903. sD = a;
  44904. }
  44905. }
  44906. else if (tN > tD) {
  44907. tN = tD;
  44908. // recompute sc for this edge
  44909. if ((-d + b) < 0.0) {
  44910. sN = 0;
  44911. }
  44912. else if ((-d + b) > a) {
  44913. sN = sD;
  44914. }
  44915. else {
  44916. sN = (-d + b);
  44917. sD = a;
  44918. }
  44919. }
  44920. // finally do the division to get sc and tc
  44921. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  44922. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  44923. // get the difference of the two closest points
  44924. var qtc = v.multiplyByFloats(tc, tc, tc);
  44925. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  44926. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  44927. if (isIntersected) {
  44928. return qtc.length();
  44929. }
  44930. return -1;
  44931. };
  44932. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  44933. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  44934. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  44935. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  44936. this.direction.normalize();
  44937. return this;
  44938. };
  44939. // Statics
  44940. Ray.Zero = function () {
  44941. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  44942. };
  44943. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  44944. var result = Ray.Zero();
  44945. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  44946. };
  44947. /**
  44948. * 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
  44949. * transformed to the given world matrix.
  44950. * @param origin The origin point
  44951. * @param end The end point
  44952. * @param world a matrix to transform the ray to. Default is the identity matrix.
  44953. */
  44954. Ray.CreateNewFromTo = function (origin, end, world) {
  44955. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  44956. var direction = end.subtract(origin);
  44957. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  44958. direction.normalize();
  44959. return Ray.Transform(new Ray(origin, direction, length), world);
  44960. };
  44961. Ray.Transform = function (ray, matrix) {
  44962. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  44963. Ray.TransformToRef(ray, matrix, result);
  44964. return result;
  44965. };
  44966. Ray.TransformToRef = function (ray, matrix, result) {
  44967. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  44968. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  44969. result.length = ray.length;
  44970. var dir = result.direction;
  44971. var len = dir.length();
  44972. if (!(len === 0 || len === 1)) {
  44973. var num = 1.0 / len;
  44974. dir.x *= num;
  44975. dir.y *= num;
  44976. dir.z *= num;
  44977. result.length *= len;
  44978. }
  44979. };
  44980. Ray.smallnum = 0.00000001;
  44981. Ray.rayl = 10e8;
  44982. return Ray;
  44983. }());
  44984. BABYLON.Ray = Ray;
  44985. })(BABYLON || (BABYLON = {}));
  44986. //# sourceMappingURL=babylon.ray.js.map
  44987. var BABYLON;
  44988. (function (BABYLON) {
  44989. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  44990. if (boxMin.x > sphereCenter.x + sphereRadius)
  44991. return false;
  44992. if (sphereCenter.x - sphereRadius > boxMax.x)
  44993. return false;
  44994. if (boxMin.y > sphereCenter.y + sphereRadius)
  44995. return false;
  44996. if (sphereCenter.y - sphereRadius > boxMax.y)
  44997. return false;
  44998. if (boxMin.z > sphereCenter.z + sphereRadius)
  44999. return false;
  45000. if (sphereCenter.z - sphereRadius > boxMax.z)
  45001. return false;
  45002. return true;
  45003. };
  45004. var getLowestRoot = (function () {
  45005. var result = { root: 0, found: false };
  45006. return function (a, b, c, maxR) {
  45007. result.root = 0;
  45008. result.found = false;
  45009. var determinant = b * b - 4.0 * a * c;
  45010. if (determinant < 0)
  45011. return result;
  45012. var sqrtD = Math.sqrt(determinant);
  45013. var r1 = (-b - sqrtD) / (2.0 * a);
  45014. var r2 = (-b + sqrtD) / (2.0 * a);
  45015. if (r1 > r2) {
  45016. var temp = r2;
  45017. r2 = r1;
  45018. r1 = temp;
  45019. }
  45020. if (r1 > 0 && r1 < maxR) {
  45021. result.root = r1;
  45022. result.found = true;
  45023. return result;
  45024. }
  45025. if (r2 > 0 && r2 < maxR) {
  45026. result.root = r2;
  45027. result.found = true;
  45028. return result;
  45029. }
  45030. return result;
  45031. };
  45032. })();
  45033. var Collider = /** @class */ (function () {
  45034. function Collider() {
  45035. this._collisionPoint = BABYLON.Vector3.Zero();
  45036. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  45037. this._tempVector = BABYLON.Vector3.Zero();
  45038. this._tempVector2 = BABYLON.Vector3.Zero();
  45039. this._tempVector3 = BABYLON.Vector3.Zero();
  45040. this._tempVector4 = BABYLON.Vector3.Zero();
  45041. this._edge = BABYLON.Vector3.Zero();
  45042. this._baseToVertex = BABYLON.Vector3.Zero();
  45043. this._destinationPoint = BABYLON.Vector3.Zero();
  45044. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  45045. this._displacementVector = BABYLON.Vector3.Zero();
  45046. this._radius = BABYLON.Vector3.One();
  45047. this._retry = 0;
  45048. this._basePointWorld = BABYLON.Vector3.Zero();
  45049. this._velocityWorld = BABYLON.Vector3.Zero();
  45050. this._normalizedVelocity = BABYLON.Vector3.Zero();
  45051. this._collisionMask = -1;
  45052. }
  45053. Object.defineProperty(Collider.prototype, "collisionMask", {
  45054. get: function () {
  45055. return this._collisionMask;
  45056. },
  45057. set: function (mask) {
  45058. this._collisionMask = !isNaN(mask) ? mask : -1;
  45059. },
  45060. enumerable: true,
  45061. configurable: true
  45062. });
  45063. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  45064. /**
  45065. * Gets the plane normal used to compute the sliding response (in local space)
  45066. */
  45067. get: function () {
  45068. return this._slidePlaneNormal;
  45069. },
  45070. enumerable: true,
  45071. configurable: true
  45072. });
  45073. // Methods
  45074. Collider.prototype._initialize = function (source, dir, e) {
  45075. this._velocity = dir;
  45076. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  45077. this._basePoint = source;
  45078. source.multiplyToRef(this._radius, this._basePointWorld);
  45079. dir.multiplyToRef(this._radius, this._velocityWorld);
  45080. this._velocityWorldLength = this._velocityWorld.length();
  45081. this._epsilon = e;
  45082. this.collisionFound = false;
  45083. };
  45084. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  45085. pa.subtractToRef(point, this._tempVector);
  45086. pb.subtractToRef(point, this._tempVector2);
  45087. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  45088. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  45089. if (d < 0)
  45090. return false;
  45091. pc.subtractToRef(point, this._tempVector3);
  45092. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  45093. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  45094. if (d < 0)
  45095. return false;
  45096. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  45097. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  45098. return d >= 0;
  45099. };
  45100. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  45101. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  45102. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  45103. if (distance > this._velocityWorldLength + max + sphereRadius) {
  45104. return false;
  45105. }
  45106. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  45107. return false;
  45108. return true;
  45109. };
  45110. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  45111. var t0;
  45112. var embeddedInPlane = false;
  45113. //defensive programming, actually not needed.
  45114. if (!trianglePlaneArray) {
  45115. trianglePlaneArray = [];
  45116. }
  45117. if (!trianglePlaneArray[faceIndex]) {
  45118. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  45119. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  45120. }
  45121. var trianglePlane = trianglePlaneArray[faceIndex];
  45122. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  45123. return;
  45124. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  45125. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  45126. if (normalDotVelocity == 0) {
  45127. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  45128. return;
  45129. embeddedInPlane = true;
  45130. t0 = 0;
  45131. }
  45132. else {
  45133. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  45134. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  45135. if (t0 > t1) {
  45136. var temp = t1;
  45137. t1 = t0;
  45138. t0 = temp;
  45139. }
  45140. if (t0 > 1.0 || t1 < 0.0)
  45141. return;
  45142. if (t0 < 0)
  45143. t0 = 0;
  45144. if (t0 > 1.0)
  45145. t0 = 1.0;
  45146. }
  45147. this._collisionPoint.copyFromFloats(0, 0, 0);
  45148. var found = false;
  45149. var t = 1.0;
  45150. if (!embeddedInPlane) {
  45151. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  45152. this._velocity.scaleToRef(t0, this._tempVector);
  45153. this._planeIntersectionPoint.addInPlace(this._tempVector);
  45154. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  45155. found = true;
  45156. t = t0;
  45157. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  45158. }
  45159. }
  45160. if (!found) {
  45161. var velocitySquaredLength = this._velocity.lengthSquared();
  45162. var a = velocitySquaredLength;
  45163. this._basePoint.subtractToRef(p1, this._tempVector);
  45164. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  45165. var c = this._tempVector.lengthSquared() - 1.0;
  45166. var lowestRoot = getLowestRoot(a, b, c, t);
  45167. if (lowestRoot.found) {
  45168. t = lowestRoot.root;
  45169. found = true;
  45170. this._collisionPoint.copyFrom(p1);
  45171. }
  45172. this._basePoint.subtractToRef(p2, this._tempVector);
  45173. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  45174. c = this._tempVector.lengthSquared() - 1.0;
  45175. lowestRoot = getLowestRoot(a, b, c, t);
  45176. if (lowestRoot.found) {
  45177. t = lowestRoot.root;
  45178. found = true;
  45179. this._collisionPoint.copyFrom(p2);
  45180. }
  45181. this._basePoint.subtractToRef(p3, this._tempVector);
  45182. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  45183. c = this._tempVector.lengthSquared() - 1.0;
  45184. lowestRoot = getLowestRoot(a, b, c, t);
  45185. if (lowestRoot.found) {
  45186. t = lowestRoot.root;
  45187. found = true;
  45188. this._collisionPoint.copyFrom(p3);
  45189. }
  45190. p2.subtractToRef(p1, this._edge);
  45191. p1.subtractToRef(this._basePoint, this._baseToVertex);
  45192. var edgeSquaredLength = this._edge.lengthSquared();
  45193. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  45194. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  45195. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  45196. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  45197. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  45198. lowestRoot = getLowestRoot(a, b, c, t);
  45199. if (lowestRoot.found) {
  45200. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  45201. if (f >= 0.0 && f <= 1.0) {
  45202. t = lowestRoot.root;
  45203. found = true;
  45204. this._edge.scaleInPlace(f);
  45205. p1.addToRef(this._edge, this._collisionPoint);
  45206. }
  45207. }
  45208. p3.subtractToRef(p2, this._edge);
  45209. p2.subtractToRef(this._basePoint, this._baseToVertex);
  45210. edgeSquaredLength = this._edge.lengthSquared();
  45211. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  45212. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  45213. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  45214. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  45215. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  45216. lowestRoot = getLowestRoot(a, b, c, t);
  45217. if (lowestRoot.found) {
  45218. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  45219. if (f >= 0.0 && f <= 1.0) {
  45220. t = lowestRoot.root;
  45221. found = true;
  45222. this._edge.scaleInPlace(f);
  45223. p2.addToRef(this._edge, this._collisionPoint);
  45224. }
  45225. }
  45226. p1.subtractToRef(p3, this._edge);
  45227. p3.subtractToRef(this._basePoint, this._baseToVertex);
  45228. edgeSquaredLength = this._edge.lengthSquared();
  45229. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  45230. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  45231. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  45232. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  45233. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  45234. lowestRoot = getLowestRoot(a, b, c, t);
  45235. if (lowestRoot.found) {
  45236. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  45237. if (f >= 0.0 && f <= 1.0) {
  45238. t = lowestRoot.root;
  45239. found = true;
  45240. this._edge.scaleInPlace(f);
  45241. p3.addToRef(this._edge, this._collisionPoint);
  45242. }
  45243. }
  45244. }
  45245. if (found) {
  45246. var distToCollision = t * this._velocity.length();
  45247. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  45248. if (!this.intersectionPoint) {
  45249. this.intersectionPoint = this._collisionPoint.clone();
  45250. }
  45251. else {
  45252. this.intersectionPoint.copyFrom(this._collisionPoint);
  45253. }
  45254. this._nearestDistance = distToCollision;
  45255. this.collisionFound = true;
  45256. }
  45257. }
  45258. };
  45259. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  45260. for (var i = indexStart; i < indexEnd; i += 3) {
  45261. var p1 = pts[indices[i] - decal];
  45262. var p2 = pts[indices[i + 1] - decal];
  45263. var p3 = pts[indices[i + 2] - decal];
  45264. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  45265. }
  45266. };
  45267. Collider.prototype._getResponse = function (pos, vel) {
  45268. pos.addToRef(vel, this._destinationPoint);
  45269. vel.scaleInPlace((this._nearestDistance / vel.length()));
  45270. this._basePoint.addToRef(vel, pos);
  45271. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  45272. this._slidePlaneNormal.normalize();
  45273. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  45274. pos.addInPlace(this._displacementVector);
  45275. this.intersectionPoint.addInPlace(this._displacementVector);
  45276. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  45277. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  45278. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  45279. };
  45280. return Collider;
  45281. }());
  45282. BABYLON.Collider = Collider;
  45283. })(BABYLON || (BABYLON = {}));
  45284. //# sourceMappingURL=babylon.collider.js.map
  45285. var BABYLON;
  45286. (function (BABYLON) {
  45287. //WebWorker code will be inserted to this variable.
  45288. BABYLON.CollisionWorker = "";
  45289. var WorkerTaskType;
  45290. (function (WorkerTaskType) {
  45291. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  45292. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  45293. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  45294. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  45295. var WorkerReplyType;
  45296. (function (WorkerReplyType) {
  45297. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  45298. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  45299. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  45300. var CollisionCoordinatorWorker = /** @class */ (function () {
  45301. function CollisionCoordinatorWorker() {
  45302. var _this = this;
  45303. this._scaledPosition = BABYLON.Vector3.Zero();
  45304. this._scaledVelocity = BABYLON.Vector3.Zero();
  45305. this.onMeshUpdated = function (transformNode) {
  45306. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  45307. };
  45308. this.onGeometryUpdated = function (geometry) {
  45309. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  45310. };
  45311. this._afterRender = function () {
  45312. if (!_this._init)
  45313. return;
  45314. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  45315. return;
  45316. }
  45317. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  45318. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  45319. if (_this._runningUpdated > 4) {
  45320. return;
  45321. }
  45322. ++_this._runningUpdated;
  45323. var payload = {
  45324. updatedMeshes: _this._addUpdateMeshesList,
  45325. updatedGeometries: _this._addUpdateGeometriesList,
  45326. removedGeometries: _this._toRemoveGeometryArray,
  45327. removedMeshes: _this._toRemoveMeshesArray
  45328. };
  45329. var message = {
  45330. payload: payload,
  45331. taskType: WorkerTaskType.UPDATE
  45332. };
  45333. var serializable = [];
  45334. for (var id in payload.updatedGeometries) {
  45335. if (payload.updatedGeometries.hasOwnProperty(id)) {
  45336. //prepare transferables
  45337. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  45338. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  45339. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  45340. }
  45341. }
  45342. _this._worker.postMessage(message, serializable);
  45343. _this._addUpdateMeshesList = {};
  45344. _this._addUpdateGeometriesList = {};
  45345. _this._toRemoveGeometryArray = [];
  45346. _this._toRemoveMeshesArray = [];
  45347. };
  45348. this._onMessageFromWorker = function (e) {
  45349. var returnData = e.data;
  45350. if (returnData.error != WorkerReplyType.SUCCESS) {
  45351. //TODO what errors can be returned from the worker?
  45352. BABYLON.Tools.Warn("error returned from worker!");
  45353. return;
  45354. }
  45355. switch (returnData.taskType) {
  45356. case WorkerTaskType.INIT:
  45357. _this._init = true;
  45358. //Update the worked with ALL of the scene's current state
  45359. _this._scene.meshes.forEach(function (mesh) {
  45360. _this.onMeshAdded(mesh);
  45361. });
  45362. _this._scene.getGeometries().forEach(function (geometry) {
  45363. _this.onGeometryAdded(geometry);
  45364. });
  45365. break;
  45366. case WorkerTaskType.UPDATE:
  45367. _this._runningUpdated--;
  45368. break;
  45369. case WorkerTaskType.COLLIDE:
  45370. var returnPayload = returnData.payload;
  45371. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  45372. return;
  45373. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  45374. if (callback) {
  45375. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  45376. if (mesh) {
  45377. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  45378. }
  45379. }
  45380. //cleanup
  45381. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  45382. break;
  45383. }
  45384. };
  45385. this._collisionsCallbackArray = [];
  45386. this._init = false;
  45387. this._runningUpdated = 0;
  45388. this._addUpdateMeshesList = {};
  45389. this._addUpdateGeometriesList = {};
  45390. this._toRemoveGeometryArray = [];
  45391. this._toRemoveMeshesArray = [];
  45392. }
  45393. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  45394. if (!this._init)
  45395. return;
  45396. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  45397. return;
  45398. position.divideToRef(collider._radius, this._scaledPosition);
  45399. displacement.divideToRef(collider._radius, this._scaledVelocity);
  45400. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  45401. var payload = {
  45402. collider: {
  45403. position: this._scaledPosition.asArray(),
  45404. velocity: this._scaledVelocity.asArray(),
  45405. radius: collider._radius.asArray()
  45406. },
  45407. collisionId: collisionIndex,
  45408. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  45409. maximumRetry: maximumRetry
  45410. };
  45411. var message = {
  45412. payload: payload,
  45413. taskType: WorkerTaskType.COLLIDE
  45414. };
  45415. this._worker.postMessage(message);
  45416. };
  45417. CollisionCoordinatorWorker.prototype.init = function (scene) {
  45418. this._scene = scene;
  45419. this._scene.registerAfterRender(this._afterRender);
  45420. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  45421. this._worker = new Worker(workerUrl);
  45422. this._worker.onmessage = this._onMessageFromWorker;
  45423. var message = {
  45424. payload: {},
  45425. taskType: WorkerTaskType.INIT
  45426. };
  45427. this._worker.postMessage(message);
  45428. };
  45429. CollisionCoordinatorWorker.prototype.destroy = function () {
  45430. this._scene.unregisterAfterRender(this._afterRender);
  45431. this._worker.terminate();
  45432. };
  45433. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  45434. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  45435. this.onMeshUpdated(mesh);
  45436. };
  45437. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  45438. this._toRemoveMeshesArray.push(mesh.uniqueId);
  45439. };
  45440. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  45441. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  45442. geometry.onGeometryUpdated = this.onGeometryUpdated;
  45443. this.onGeometryUpdated(geometry);
  45444. };
  45445. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  45446. this._toRemoveGeometryArray.push(geometry.id);
  45447. };
  45448. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  45449. var submeshes = [];
  45450. if (mesh.subMeshes) {
  45451. submeshes = mesh.subMeshes.map(function (sm, idx) {
  45452. var boundingInfo = sm.getBoundingInfo();
  45453. return {
  45454. position: idx,
  45455. verticesStart: sm.verticesStart,
  45456. verticesCount: sm.verticesCount,
  45457. indexStart: sm.indexStart,
  45458. indexCount: sm.indexCount,
  45459. hasMaterial: !!sm.getMaterial(),
  45460. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  45461. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  45462. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  45463. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  45464. };
  45465. });
  45466. }
  45467. var geometryId = null;
  45468. if (mesh instanceof BABYLON.Mesh) {
  45469. var geometry = mesh.geometry;
  45470. geometryId = geometry ? geometry.id : null;
  45471. }
  45472. else if (mesh instanceof BABYLON.InstancedMesh) {
  45473. var geometry = mesh.sourceMesh.geometry;
  45474. geometryId = geometry ? geometry.id : null;
  45475. }
  45476. var boundingInfo = mesh.getBoundingInfo();
  45477. return {
  45478. uniqueId: mesh.uniqueId,
  45479. id: mesh.id,
  45480. name: mesh.name,
  45481. geometryId: geometryId,
  45482. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  45483. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  45484. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  45485. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  45486. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  45487. subMeshes: submeshes,
  45488. checkCollisions: mesh.checkCollisions
  45489. };
  45490. };
  45491. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  45492. return {
  45493. id: geometry.id,
  45494. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  45495. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  45496. indices: new Uint32Array(geometry.getIndices() || []),
  45497. };
  45498. };
  45499. return CollisionCoordinatorWorker;
  45500. }());
  45501. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  45502. var CollisionCoordinatorLegacy = /** @class */ (function () {
  45503. function CollisionCoordinatorLegacy() {
  45504. this._scaledPosition = BABYLON.Vector3.Zero();
  45505. this._scaledVelocity = BABYLON.Vector3.Zero();
  45506. this._finalPosition = BABYLON.Vector3.Zero();
  45507. }
  45508. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  45509. position.divideToRef(collider._radius, this._scaledPosition);
  45510. displacement.divideToRef(collider._radius, this._scaledVelocity);
  45511. collider.collidedMesh = null;
  45512. collider._retry = 0;
  45513. collider._initialVelocity = this._scaledVelocity;
  45514. collider._initialPosition = this._scaledPosition;
  45515. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  45516. this._finalPosition.multiplyInPlace(collider._radius);
  45517. //run the callback
  45518. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  45519. };
  45520. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  45521. this._scene = scene;
  45522. };
  45523. CollisionCoordinatorLegacy.prototype.destroy = function () {
  45524. //Legacy need no destruction method.
  45525. };
  45526. //No update in legacy mode
  45527. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  45528. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  45529. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  45530. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  45531. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  45532. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  45533. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  45534. if (excludedMesh === void 0) { excludedMesh = null; }
  45535. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  45536. if (collider._retry >= maximumRetry) {
  45537. finalPosition.copyFrom(position);
  45538. return;
  45539. }
  45540. // Check if this is a mesh else camera or -1
  45541. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  45542. collider._initialize(position, velocity, closeDistance);
  45543. // Check all meshes
  45544. for (var index = 0; index < this._scene.meshes.length; index++) {
  45545. var mesh = this._scene.meshes[index];
  45546. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  45547. mesh._checkCollision(collider);
  45548. }
  45549. }
  45550. if (!collider.collisionFound) {
  45551. position.addToRef(velocity, finalPosition);
  45552. return;
  45553. }
  45554. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  45555. collider._getResponse(position, velocity);
  45556. }
  45557. if (velocity.length() <= closeDistance) {
  45558. finalPosition.copyFrom(position);
  45559. return;
  45560. }
  45561. collider._retry++;
  45562. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  45563. };
  45564. return CollisionCoordinatorLegacy;
  45565. }());
  45566. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  45567. })(BABYLON || (BABYLON = {}));
  45568. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  45569. var BABYLON;
  45570. (function (BABYLON) {
  45571. var Particle = /** @class */ (function () {
  45572. function Particle(particleSystem) {
  45573. this.particleSystem = particleSystem;
  45574. this.position = BABYLON.Vector3.Zero();
  45575. this.direction = BABYLON.Vector3.Zero();
  45576. this.color = new BABYLON.Color4(0, 0, 0, 0);
  45577. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  45578. this.lifeTime = 1.0;
  45579. this.age = 0;
  45580. this.size = 0;
  45581. this.angle = 0;
  45582. this.angularSpeed = 0;
  45583. this._currentFrameCounter = 0;
  45584. this.cellIndex = 0;
  45585. if (!this.particleSystem.isAnimationSheetEnabled) {
  45586. return;
  45587. }
  45588. this.cellIndex = this.particleSystem.startSpriteCellID;
  45589. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  45590. this.updateCellIndex = this.updateCellIndexWithSpeedCalculated;
  45591. }
  45592. else {
  45593. this.updateCellIndex = this.updateCellIndexWithCustomSpeed;
  45594. }
  45595. }
  45596. Particle.prototype.updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  45597. // (ageOffset / scaledUpdateSpeed) / available cells
  45598. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  45599. this._currentFrameCounter += scaledUpdateSpeed;
  45600. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  45601. this._currentFrameCounter = 0;
  45602. this.cellIndex++;
  45603. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  45604. this.cellIndex = this.particleSystem.endSpriteCellID;
  45605. }
  45606. }
  45607. };
  45608. Particle.prototype.updateCellIndexWithCustomSpeed = function () {
  45609. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  45610. this.cellIndex++;
  45611. this._currentFrameCounter = 0;
  45612. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  45613. if (this.particleSystem.spriteCellLoop) {
  45614. this.cellIndex = this.particleSystem.startSpriteCellID;
  45615. }
  45616. else {
  45617. this.cellIndex = this.particleSystem.endSpriteCellID;
  45618. }
  45619. }
  45620. }
  45621. else {
  45622. this._currentFrameCounter++;
  45623. }
  45624. };
  45625. Particle.prototype.copyTo = function (other) {
  45626. other.position.copyFrom(this.position);
  45627. other.direction.copyFrom(this.direction);
  45628. other.color.copyFrom(this.color);
  45629. other.colorStep.copyFrom(this.colorStep);
  45630. other.lifeTime = this.lifeTime;
  45631. other.age = this.age;
  45632. other.size = this.size;
  45633. other.angle = this.angle;
  45634. other.angularSpeed = this.angularSpeed;
  45635. other.particleSystem = this.particleSystem;
  45636. other.cellIndex = this.cellIndex;
  45637. };
  45638. return Particle;
  45639. }());
  45640. BABYLON.Particle = Particle;
  45641. })(BABYLON || (BABYLON = {}));
  45642. //# sourceMappingURL=babylon.particle.js.map
  45643. var BABYLON;
  45644. (function (BABYLON) {
  45645. var randomNumber = function (min, max) {
  45646. if (min === max) {
  45647. return (min);
  45648. }
  45649. var random = Math.random();
  45650. return ((random * (max - min)) + min);
  45651. };
  45652. var ParticleSystem = /** @class */ (function () {
  45653. // end of sheet animation
  45654. function ParticleSystem(name, capacity, scene, customEffect, _isAnimationSheetEnabled, epsilon) {
  45655. if (customEffect === void 0) { customEffect = null; }
  45656. if (_isAnimationSheetEnabled === void 0) { _isAnimationSheetEnabled = false; }
  45657. if (epsilon === void 0) { epsilon = 0.01; }
  45658. var _this = this;
  45659. this.name = name;
  45660. this._isAnimationSheetEnabled = _isAnimationSheetEnabled;
  45661. // Members
  45662. this.animations = [];
  45663. this.renderingGroupId = 0;
  45664. this.emitter = null;
  45665. this.emitRate = 10;
  45666. this.manualEmitCount = -1;
  45667. this.updateSpeed = 0.01;
  45668. this.targetStopDuration = 0;
  45669. this.disposeOnStop = false;
  45670. this.minEmitPower = 1;
  45671. this.maxEmitPower = 1;
  45672. this.minLifeTime = 1;
  45673. this.maxLifeTime = 1;
  45674. this.minSize = 1;
  45675. this.maxSize = 1;
  45676. this.minAngularSpeed = 0;
  45677. this.maxAngularSpeed = 0;
  45678. this.layerMask = 0x0FFFFFFF;
  45679. this.customShader = null;
  45680. this.preventAutoStart = false;
  45681. /**
  45682. * An event triggered when the system is disposed.
  45683. * @type {BABYLON.Observable}
  45684. */
  45685. this.onDisposeObservable = new BABYLON.Observable();
  45686. this.onAnimationEnd = null;
  45687. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  45688. this.forceDepthWrite = false;
  45689. this.gravity = BABYLON.Vector3.Zero();
  45690. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  45691. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  45692. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  45693. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  45694. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  45695. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  45696. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  45697. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  45698. this.particles = new Array();
  45699. this._stockParticles = new Array();
  45700. this._newPartsExcess = 0;
  45701. this._vertexBuffers = {};
  45702. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  45703. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  45704. this._scaledDirection = BABYLON.Vector3.Zero();
  45705. this._scaledGravity = BABYLON.Vector3.Zero();
  45706. this._currentRenderId = -1;
  45707. this._started = false;
  45708. this._stopped = false;
  45709. this._actualFrame = 0;
  45710. // sheet animation
  45711. this.startSpriteCellID = 0;
  45712. this.endSpriteCellID = 0;
  45713. this.spriteCellLoop = true;
  45714. this.spriteCellChangeSpeed = 0;
  45715. this.spriteCellWidth = 0;
  45716. this.spriteCellHeight = 0;
  45717. this._vertexBufferSize = 11;
  45718. this.appendParticleVertexes = null;
  45719. this.id = name;
  45720. this._capacity = capacity;
  45721. this._epsilon = epsilon;
  45722. if (_isAnimationSheetEnabled) {
  45723. this._vertexBufferSize = 12;
  45724. }
  45725. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  45726. this._customEffect = customEffect;
  45727. scene.particleSystems.push(this);
  45728. this._createIndexBuffer();
  45729. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  45730. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  45731. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  45732. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  45733. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  45734. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  45735. if (this._isAnimationSheetEnabled) {
  45736. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  45737. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  45738. }
  45739. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  45740. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  45741. this._vertexBuffers["options"] = options;
  45742. // Default behaviors
  45743. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  45744. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  45745. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  45746. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  45747. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  45748. };
  45749. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  45750. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  45751. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  45752. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  45753. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  45754. };
  45755. this.updateFunction = function (particles) {
  45756. for (var index = 0; index < particles.length; index++) {
  45757. var particle = particles[index];
  45758. particle.age += _this._scaledUpdateSpeed;
  45759. if (particle.age >= particle.lifeTime) {
  45760. _this.recycleParticle(particle);
  45761. index--;
  45762. continue;
  45763. }
  45764. else {
  45765. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  45766. particle.color.addInPlace(_this._scaledColorStep);
  45767. if (particle.color.a < 0)
  45768. particle.color.a = 0;
  45769. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  45770. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  45771. particle.position.addInPlace(_this._scaledDirection);
  45772. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  45773. particle.direction.addInPlace(_this._scaledGravity);
  45774. if (_this._isAnimationSheetEnabled) {
  45775. particle.updateCellIndex(_this._scaledUpdateSpeed);
  45776. }
  45777. }
  45778. }
  45779. };
  45780. }
  45781. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  45782. set: function (callback) {
  45783. if (this._onDisposeObserver) {
  45784. this.onDisposeObservable.remove(this._onDisposeObserver);
  45785. }
  45786. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  45787. },
  45788. enumerable: true,
  45789. configurable: true
  45790. });
  45791. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  45792. get: function () {
  45793. return this._isAnimationSheetEnabled;
  45794. },
  45795. enumerable: true,
  45796. configurable: true
  45797. });
  45798. ParticleSystem.prototype._createIndexBuffer = function () {
  45799. var indices = [];
  45800. var index = 0;
  45801. for (var count = 0; count < this._capacity; count++) {
  45802. indices.push(index);
  45803. indices.push(index + 1);
  45804. indices.push(index + 2);
  45805. indices.push(index);
  45806. indices.push(index + 2);
  45807. indices.push(index + 3);
  45808. index += 4;
  45809. }
  45810. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  45811. };
  45812. ParticleSystem.prototype.recycleParticle = function (particle) {
  45813. var lastParticle = this.particles.pop();
  45814. if (lastParticle !== particle) {
  45815. lastParticle.copyTo(particle);
  45816. this._stockParticles.push(lastParticle);
  45817. }
  45818. };
  45819. ParticleSystem.prototype.getCapacity = function () {
  45820. return this._capacity;
  45821. };
  45822. ParticleSystem.prototype.isAlive = function () {
  45823. return this._alive;
  45824. };
  45825. ParticleSystem.prototype.isStarted = function () {
  45826. return this._started;
  45827. };
  45828. ParticleSystem.prototype.start = function () {
  45829. this._started = true;
  45830. this._stopped = false;
  45831. this._actualFrame = 0;
  45832. };
  45833. ParticleSystem.prototype.stop = function () {
  45834. this._stopped = true;
  45835. };
  45836. // animation sheet
  45837. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  45838. var offset = index * this._vertexBufferSize;
  45839. this._vertexData[offset] = particle.position.x;
  45840. this._vertexData[offset + 1] = particle.position.y;
  45841. this._vertexData[offset + 2] = particle.position.z;
  45842. this._vertexData[offset + 3] = particle.color.r;
  45843. this._vertexData[offset + 4] = particle.color.g;
  45844. this._vertexData[offset + 5] = particle.color.b;
  45845. this._vertexData[offset + 6] = particle.color.a;
  45846. this._vertexData[offset + 7] = particle.angle;
  45847. this._vertexData[offset + 8] = particle.size;
  45848. this._vertexData[offset + 9] = offsetX;
  45849. this._vertexData[offset + 10] = offsetY;
  45850. };
  45851. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  45852. if (offsetX === 0)
  45853. offsetX = this._epsilon;
  45854. else if (offsetX === 1)
  45855. offsetX = 1 - this._epsilon;
  45856. if (offsetY === 0)
  45857. offsetY = this._epsilon;
  45858. else if (offsetY === 1)
  45859. offsetY = 1 - this._epsilon;
  45860. var offset = index * this._vertexBufferSize;
  45861. this._vertexData[offset] = particle.position.x;
  45862. this._vertexData[offset + 1] = particle.position.y;
  45863. this._vertexData[offset + 2] = particle.position.z;
  45864. this._vertexData[offset + 3] = particle.color.r;
  45865. this._vertexData[offset + 4] = particle.color.g;
  45866. this._vertexData[offset + 5] = particle.color.b;
  45867. this._vertexData[offset + 6] = particle.color.a;
  45868. this._vertexData[offset + 7] = particle.angle;
  45869. this._vertexData[offset + 8] = particle.size;
  45870. this._vertexData[offset + 9] = offsetX;
  45871. this._vertexData[offset + 10] = offsetY;
  45872. this._vertexData[offset + 11] = particle.cellIndex;
  45873. };
  45874. ParticleSystem.prototype._update = function (newParticles) {
  45875. // Update current
  45876. this._alive = this.particles.length > 0;
  45877. this.updateFunction(this.particles);
  45878. // Add new ones
  45879. var worldMatrix;
  45880. if (this.emitter.position) {
  45881. var emitterMesh = this.emitter;
  45882. worldMatrix = emitterMesh.getWorldMatrix();
  45883. }
  45884. else {
  45885. var emitterPosition = this.emitter;
  45886. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  45887. }
  45888. var particle;
  45889. for (var index = 0; index < newParticles; index++) {
  45890. if (this.particles.length === this._capacity) {
  45891. break;
  45892. }
  45893. if (this._stockParticles.length !== 0) {
  45894. particle = this._stockParticles.pop();
  45895. particle.age = 0;
  45896. particle.cellIndex = this.startSpriteCellID;
  45897. }
  45898. else {
  45899. particle = new BABYLON.Particle(this);
  45900. }
  45901. this.particles.push(particle);
  45902. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  45903. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  45904. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  45905. particle.size = randomNumber(this.minSize, this.maxSize);
  45906. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  45907. this.startPositionFunction(worldMatrix, particle.position, particle);
  45908. var step = randomNumber(0, 1.0);
  45909. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  45910. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  45911. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  45912. }
  45913. };
  45914. ParticleSystem.prototype._getEffect = function () {
  45915. if (this._customEffect) {
  45916. return this._customEffect;
  45917. }
  45918. ;
  45919. var defines = [];
  45920. if (this._scene.clipPlane) {
  45921. defines.push("#define CLIPPLANE");
  45922. }
  45923. if (this._isAnimationSheetEnabled) {
  45924. defines.push("#define ANIMATESHEET");
  45925. }
  45926. // Effect
  45927. var join = defines.join("\n");
  45928. if (this._cachedDefines !== join) {
  45929. this._cachedDefines = join;
  45930. var attributesNamesOrOptions;
  45931. var effectCreationOption;
  45932. if (this._isAnimationSheetEnabled) {
  45933. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  45934. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  45935. }
  45936. else {
  45937. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  45938. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  45939. }
  45940. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  45941. }
  45942. return this._effect;
  45943. };
  45944. ParticleSystem.prototype.animate = function () {
  45945. if (!this._started)
  45946. return;
  45947. var effect = this._getEffect();
  45948. // Check
  45949. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  45950. return;
  45951. if (this._currentRenderId === this._scene.getRenderId()) {
  45952. return;
  45953. }
  45954. this._currentRenderId = this._scene.getRenderId();
  45955. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  45956. // determine the number of particles we need to create
  45957. var newParticles;
  45958. if (this.manualEmitCount > -1) {
  45959. newParticles = this.manualEmitCount;
  45960. this._newPartsExcess = 0;
  45961. this.manualEmitCount = 0;
  45962. }
  45963. else {
  45964. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  45965. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  45966. }
  45967. if (this._newPartsExcess > 1.0) {
  45968. newParticles += this._newPartsExcess >> 0;
  45969. this._newPartsExcess -= this._newPartsExcess >> 0;
  45970. }
  45971. this._alive = false;
  45972. if (!this._stopped) {
  45973. this._actualFrame += this._scaledUpdateSpeed;
  45974. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  45975. this.stop();
  45976. }
  45977. else {
  45978. newParticles = 0;
  45979. }
  45980. this._update(newParticles);
  45981. // Stopped?
  45982. if (this._stopped) {
  45983. if (!this._alive) {
  45984. this._started = false;
  45985. if (this.onAnimationEnd) {
  45986. this.onAnimationEnd();
  45987. }
  45988. if (this.disposeOnStop) {
  45989. this._scene._toBeDisposed.push(this);
  45990. }
  45991. }
  45992. }
  45993. // Animation sheet
  45994. if (this._isAnimationSheetEnabled) {
  45995. this.appendParticleVertexes = this.appenedParticleVertexesWithSheet;
  45996. }
  45997. else {
  45998. this.appendParticleVertexes = this.appenedParticleVertexesNoSheet;
  45999. }
  46000. // Update VBO
  46001. var offset = 0;
  46002. for (var index = 0; index < this.particles.length; index++) {
  46003. var particle = this.particles[index];
  46004. this.appendParticleVertexes(offset, particle);
  46005. offset += 4;
  46006. }
  46007. if (this._vertexBuffer) {
  46008. this._vertexBuffer.update(this._vertexData);
  46009. }
  46010. };
  46011. ParticleSystem.prototype.appenedParticleVertexesWithSheet = function (offset, particle) {
  46012. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  46013. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  46014. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  46015. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  46016. };
  46017. ParticleSystem.prototype.appenedParticleVertexesNoSheet = function (offset, particle) {
  46018. this._appendParticleVertex(offset++, particle, 0, 0);
  46019. this._appendParticleVertex(offset++, particle, 1, 0);
  46020. this._appendParticleVertex(offset++, particle, 1, 1);
  46021. this._appendParticleVertex(offset++, particle, 0, 1);
  46022. };
  46023. ParticleSystem.prototype.rebuild = function () {
  46024. this._createIndexBuffer();
  46025. if (this._vertexBuffer) {
  46026. this._vertexBuffer._rebuild();
  46027. }
  46028. };
  46029. ParticleSystem.prototype.render = function () {
  46030. var effect = this._getEffect();
  46031. // Check
  46032. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  46033. return 0;
  46034. var engine = this._scene.getEngine();
  46035. // Render
  46036. engine.enableEffect(effect);
  46037. engine.setState(false);
  46038. var viewMatrix = this._scene.getViewMatrix();
  46039. effect.setTexture("diffuseSampler", this.particleTexture);
  46040. effect.setMatrix("view", viewMatrix);
  46041. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  46042. if (this._isAnimationSheetEnabled) {
  46043. var baseSize = this.particleTexture.getBaseSize();
  46044. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  46045. }
  46046. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  46047. if (this._scene.clipPlane) {
  46048. var clipPlane = this._scene.clipPlane;
  46049. var invView = viewMatrix.clone();
  46050. invView.invert();
  46051. effect.setMatrix("invView", invView);
  46052. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  46053. }
  46054. // VBOs
  46055. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  46056. // Draw order
  46057. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  46058. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  46059. }
  46060. else {
  46061. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  46062. }
  46063. if (this.forceDepthWrite) {
  46064. engine.setDepthWrite(true);
  46065. }
  46066. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this.particles.length * 6);
  46067. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  46068. return this.particles.length;
  46069. };
  46070. ParticleSystem.prototype.dispose = function () {
  46071. if (this._vertexBuffer) {
  46072. this._vertexBuffer.dispose();
  46073. this._vertexBuffer = null;
  46074. }
  46075. if (this._indexBuffer) {
  46076. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  46077. this._indexBuffer = null;
  46078. }
  46079. if (this.particleTexture) {
  46080. this.particleTexture.dispose();
  46081. this.particleTexture = null;
  46082. }
  46083. // Remove from scene
  46084. var index = this._scene.particleSystems.indexOf(this);
  46085. if (index > -1) {
  46086. this._scene.particleSystems.splice(index, 1);
  46087. }
  46088. // Callback
  46089. this.onDisposeObservable.notifyObservers(this);
  46090. this.onDisposeObservable.clear();
  46091. };
  46092. // Clone
  46093. ParticleSystem.prototype.clone = function (name, newEmitter) {
  46094. var custom = null;
  46095. var program = null;
  46096. if (this.customShader != null) {
  46097. program = this.customShader;
  46098. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  46099. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  46100. }
  46101. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  46102. result.customShader = program;
  46103. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  46104. if (newEmitter === undefined) {
  46105. newEmitter = this.emitter;
  46106. }
  46107. result.emitter = newEmitter;
  46108. if (this.particleTexture) {
  46109. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  46110. }
  46111. if (!this.preventAutoStart) {
  46112. result.start();
  46113. }
  46114. return result;
  46115. };
  46116. ParticleSystem.prototype.serialize = function () {
  46117. var serializationObject = {};
  46118. serializationObject.name = this.name;
  46119. serializationObject.id = this.id;
  46120. // Emitter
  46121. if (this.emitter.position) {
  46122. var emitterMesh = this.emitter;
  46123. serializationObject.emitterId = emitterMesh.id;
  46124. }
  46125. else {
  46126. var emitterPosition = this.emitter;
  46127. serializationObject.emitter = emitterPosition.asArray();
  46128. }
  46129. serializationObject.capacity = this.getCapacity();
  46130. if (this.particleTexture) {
  46131. serializationObject.textureName = this.particleTexture.name;
  46132. }
  46133. // Animations
  46134. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  46135. // Particle system
  46136. serializationObject.minAngularSpeed = this.minAngularSpeed;
  46137. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  46138. serializationObject.minSize = this.minSize;
  46139. serializationObject.maxSize = this.maxSize;
  46140. serializationObject.minEmitPower = this.minEmitPower;
  46141. serializationObject.maxEmitPower = this.maxEmitPower;
  46142. serializationObject.minLifeTime = this.minLifeTime;
  46143. serializationObject.maxLifeTime = this.maxLifeTime;
  46144. serializationObject.emitRate = this.emitRate;
  46145. serializationObject.minEmitBox = this.minEmitBox.asArray();
  46146. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  46147. serializationObject.gravity = this.gravity.asArray();
  46148. serializationObject.direction1 = this.direction1.asArray();
  46149. serializationObject.direction2 = this.direction2.asArray();
  46150. serializationObject.color1 = this.color1.asArray();
  46151. serializationObject.color2 = this.color2.asArray();
  46152. serializationObject.colorDead = this.colorDead.asArray();
  46153. serializationObject.updateSpeed = this.updateSpeed;
  46154. serializationObject.targetStopDuration = this.targetStopDuration;
  46155. serializationObject.textureMask = this.textureMask.asArray();
  46156. serializationObject.blendMode = this.blendMode;
  46157. serializationObject.customShader = this.customShader;
  46158. serializationObject.preventAutoStart = this.preventAutoStart;
  46159. serializationObject.startSpriteCellID = this.startSpriteCellID;
  46160. serializationObject.endSpriteCellID = this.endSpriteCellID;
  46161. serializationObject.spriteCellLoop = this.spriteCellLoop;
  46162. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  46163. serializationObject.spriteCellWidth = this.spriteCellWidth;
  46164. serializationObject.spriteCellHeight = this.spriteCellHeight;
  46165. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  46166. return serializationObject;
  46167. };
  46168. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  46169. var name = parsedParticleSystem.name;
  46170. var custom = null;
  46171. var program = null;
  46172. if (parsedParticleSystem.customShader) {
  46173. program = parsedParticleSystem.customShader;
  46174. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  46175. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  46176. }
  46177. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  46178. particleSystem.customShader = program;
  46179. if (parsedParticleSystem.id) {
  46180. particleSystem.id = parsedParticleSystem.id;
  46181. }
  46182. // Auto start
  46183. if (parsedParticleSystem.preventAutoStart) {
  46184. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  46185. }
  46186. // Texture
  46187. if (parsedParticleSystem.textureName) {
  46188. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  46189. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  46190. }
  46191. // Emitter
  46192. if (parsedParticleSystem.emitterId) {
  46193. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  46194. }
  46195. else {
  46196. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  46197. }
  46198. // Animations
  46199. if (parsedParticleSystem.animations) {
  46200. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  46201. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  46202. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  46203. }
  46204. }
  46205. if (parsedParticleSystem.autoAnimate) {
  46206. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  46207. }
  46208. // Particle system
  46209. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  46210. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  46211. particleSystem.minSize = parsedParticleSystem.minSize;
  46212. particleSystem.maxSize = parsedParticleSystem.maxSize;
  46213. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  46214. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  46215. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  46216. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  46217. particleSystem.emitRate = parsedParticleSystem.emitRate;
  46218. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  46219. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  46220. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  46221. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  46222. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  46223. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  46224. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  46225. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  46226. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  46227. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  46228. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  46229. particleSystem.blendMode = parsedParticleSystem.blendMode;
  46230. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  46231. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  46232. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  46233. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  46234. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  46235. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  46236. if (!particleSystem.preventAutoStart) {
  46237. particleSystem.start();
  46238. }
  46239. return particleSystem;
  46240. };
  46241. // Statics
  46242. ParticleSystem.BLENDMODE_ONEONE = 0;
  46243. ParticleSystem.BLENDMODE_STANDARD = 1;
  46244. return ParticleSystem;
  46245. }());
  46246. BABYLON.ParticleSystem = ParticleSystem;
  46247. })(BABYLON || (BABYLON = {}));
  46248. //# sourceMappingURL=babylon.particleSystem.js.map
  46249. var BABYLON;
  46250. (function (BABYLON) {
  46251. var GPUParticleSystem = /** @class */ (function () {
  46252. function GPUParticleSystem(name, capacity, scene) {
  46253. this.name = name;
  46254. this.emitter = null;
  46255. this.renderingGroupId = 0;
  46256. this.layerMask = 0x0FFFFFFF; // TODO
  46257. this._updateVertexBuffers = {};
  46258. this._renderVertexBuffers = {};
  46259. this._currentRenderId = -1;
  46260. this._started = true;
  46261. /**
  46262. * An event triggered when the system is disposed.
  46263. * @type {BABYLON.Observable}
  46264. */
  46265. this.onDisposeObservable = new BABYLON.Observable();
  46266. this.id = name;
  46267. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  46268. this._capacity = capacity;
  46269. this._engine = this._scene.getEngine();
  46270. this._scene.particleSystems.push(this);
  46271. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "velocity"], [], [], this._scene.getEngine());
  46272. var updateEffectOptions = {
  46273. attributes: ["position", "age", "life", "velocity"],
  46274. uniformsNames: [],
  46275. uniformBuffersNames: [],
  46276. samplers: [],
  46277. defines: "",
  46278. fallbacks: null,
  46279. onCompiled: null,
  46280. onError: null,
  46281. indexParameters: null,
  46282. maxSimultaneousLights: 0,
  46283. transformFeedbackVaryings: ["outPosition", "outAge", "outLife", "outVelocity"]
  46284. };
  46285. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", updateEffectOptions, this._scene.getEngine());
  46286. }
  46287. GPUParticleSystem.prototype.isStarted = function () {
  46288. return this._started;
  46289. };
  46290. GPUParticleSystem.prototype.start = function () {
  46291. this._started = true;
  46292. };
  46293. GPUParticleSystem.prototype.stop = function () {
  46294. this._started = false;
  46295. };
  46296. GPUParticleSystem.prototype.animate = function () {
  46297. // Do nothing
  46298. };
  46299. GPUParticleSystem.prototype._initialize = function () {
  46300. if (this._renderVAO) {
  46301. return;
  46302. }
  46303. var data = new Array();
  46304. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  46305. // position
  46306. data.push(0.0);
  46307. data.push(0.0);
  46308. data.push(0.0);
  46309. var life = 1 + Math.random() * 10; // TODO: var
  46310. data.push(life + 1); // create the particle as a dead one to create a new one at start
  46311. data.push(life);
  46312. // velocity
  46313. data.push(0.0);
  46314. data.push(0.0);
  46315. data.push(0.0);
  46316. }
  46317. // Update VAO
  46318. this._updateBuffer = new BABYLON.Buffer(this._scene.getEngine(), data, false, 0);
  46319. this._updateVertexBuffers["position"] = this._updateBuffer.createVertexBuffer("position", 0, 3, 3);
  46320. this._updateVertexBuffers["age"] = this._updateBuffer.createVertexBuffer("age", 3, 1, 1);
  46321. this._updateVertexBuffers["life"] = this._updateBuffer.createVertexBuffer("life", 4, 1, 1);
  46322. this._updateVertexBuffers["velocity"] = this._updateBuffer.createVertexBuffer("velocity", 5, 3, 3);
  46323. this._updateVAO = this._engine.recordVertexArrayObject(this._updateVertexBuffers, null, this._updateEffect);
  46324. this._engine.bindArrayBuffer(null);
  46325. // Render VAO
  46326. this._renderBuffer = new BABYLON.Buffer(this._scene.getEngine(), data, false, 0);
  46327. this._renderVertexBuffers["position"] = this._renderBuffer.createVertexBuffer("position", 0, 3, 3);
  46328. this._renderVertexBuffers["age"] = this._renderBuffer.createVertexBuffer("age", 3, 1, 1);
  46329. this._renderVertexBuffers["life"] = this._renderBuffer.createVertexBuffer("life", 4, 1, 1);
  46330. this._renderVertexBuffers["velocity"] = this._renderBuffer.createVertexBuffer("velocity", 5, 3, 3);
  46331. this._renderVAO = this._engine.recordVertexArrayObject(this._renderVertexBuffers, null, this._renderEffect);
  46332. this._engine.bindArrayBuffer(null);
  46333. // Links
  46334. this._sourceVAO = this._updateVAO;
  46335. this._targetVAO = this._renderVAO;
  46336. this._sourceBuffer = this._updateBuffer;
  46337. this._targetBuffer = this._renderBuffer;
  46338. };
  46339. GPUParticleSystem.prototype.render = function () {
  46340. if (!this.emitter || !this._updateEffect.isReady() || !this._renderEffect.isReady()) {
  46341. return 0;
  46342. }
  46343. // Get everything ready to render
  46344. this._initialize();
  46345. if (this._currentRenderId === this._scene.getRenderId()) {
  46346. return 0;
  46347. }
  46348. this._currentRenderId = this._scene.getRenderId();
  46349. // Enable update effect
  46350. this._engine.enableEffect(this._updateEffect);
  46351. this._engine.setState(false);
  46352. // Bind source VAO
  46353. this._engine.bindVertexArrayObject(this._sourceVAO, null);
  46354. // Update
  46355. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  46356. this._engine.setRasterizerState(false);
  46357. this._engine.beginTransformFeedback();
  46358. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._capacity);
  46359. this._engine.endTransformFeedback();
  46360. this._engine.setRasterizerState(true);
  46361. this._engine.bindTransformFeedbackBuffer(null);
  46362. // Enable render effect
  46363. this._engine.enableEffect(this._renderEffect);
  46364. // Bind source VAO
  46365. this._engine.bindVertexArrayObject(this._targetVAO, null);
  46366. // Render
  46367. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._capacity);
  46368. // Switch VAOs
  46369. var tmpVAO = this._sourceVAO;
  46370. this._sourceVAO = this._targetVAO;
  46371. this._targetVAO = tmpVAO;
  46372. // Switch buffers
  46373. var tmpBuffer = this._sourceBuffer;
  46374. this._sourceBuffer = this._targetBuffer;
  46375. this._targetBuffer = tmpBuffer;
  46376. return 0;
  46377. };
  46378. GPUParticleSystem.prototype.rebuild = function () {
  46379. };
  46380. GPUParticleSystem.prototype.dispose = function () {
  46381. var index = this._scene.particleSystems.indexOf(this);
  46382. if (index > -1) {
  46383. this._scene.particleSystems.splice(index, 1);
  46384. }
  46385. //TODO: this._dataBuffer.dispose();
  46386. // Callback
  46387. this.onDisposeObservable.notifyObservers(this);
  46388. this.onDisposeObservable.clear();
  46389. };
  46390. //TODO: Clone / Parse / serialize
  46391. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  46392. return null;
  46393. };
  46394. GPUParticleSystem.prototype.serialize = function () {
  46395. };
  46396. return GPUParticleSystem;
  46397. }());
  46398. BABYLON.GPUParticleSystem = GPUParticleSystem;
  46399. })(BABYLON || (BABYLON = {}));
  46400. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  46401. var BABYLON;
  46402. (function (BABYLON) {
  46403. var SolidParticle = /** @class */ (function () {
  46404. /**
  46405. * Creates a Solid Particle object.
  46406. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  46407. * `particleIndex` (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  46408. * `positionIndex` (integer) is the starting index of the particle vertices in the SPS "positions" array.
  46409. * `indiceIndex` (integer) is the starting index of the particle indices in the SPS "indices" array.
  46410. * `model` (ModelShape) is a reference to the model shape on what the particle is designed.
  46411. * `shapeId` (integer) is the model shape identifier in the SPS.
  46412. * `idxInShape` (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  46413. * `modelBoundingInfo` is the reference to the model BoundingInfo used for intersection computations.
  46414. */
  46415. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  46416. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  46417. this.idx = 0; // particle global index
  46418. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0); // color
  46419. this.position = BABYLON.Vector3.Zero(); // position
  46420. this.rotation = BABYLON.Vector3.Zero(); // rotation
  46421. this.scaling = BABYLON.Vector3.One(); // scaling
  46422. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0); // uvs
  46423. this.velocity = BABYLON.Vector3.Zero(); // velocity
  46424. this.pivot = BABYLON.Vector3.Zero(); // pivot point in the particle local space
  46425. this.alive = true; // alive
  46426. this.isVisible = true; // visibility
  46427. this._pos = 0; // index of this particle in the global "positions" array
  46428. this._ind = 0; // index of this particle in the global "indices" array
  46429. this.shapeId = 0; // model shape id
  46430. this.idxInShape = 0; // index of the particle in its shape id
  46431. this._stillInvisible = false; // still set as invisible in order to skip useless computations
  46432. this.idx = particleIndex;
  46433. this._pos = positionIndex;
  46434. this._ind = indiceIndex;
  46435. this._model = model;
  46436. this.shapeId = shapeId;
  46437. this.idxInShape = idxInShape;
  46438. this._sps = sps;
  46439. if (modelBoundingInfo) {
  46440. this._modelBoundingInfo = modelBoundingInfo;
  46441. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  46442. }
  46443. }
  46444. Object.defineProperty(SolidParticle.prototype, "scale", {
  46445. /**
  46446. * legacy support, changed scale to scaling
  46447. */
  46448. get: function () {
  46449. return this.scaling;
  46450. },
  46451. set: function (scale) {
  46452. this.scaling = scale;
  46453. },
  46454. enumerable: true,
  46455. configurable: true
  46456. });
  46457. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  46458. /**
  46459. * legacy support, changed quaternion to rotationQuaternion
  46460. */
  46461. get: function () {
  46462. return this.rotationQuaternion;
  46463. },
  46464. set: function (q) {
  46465. this.rotationQuaternion = q;
  46466. },
  46467. enumerable: true,
  46468. configurable: true
  46469. });
  46470. /**
  46471. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  46472. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  46473. * `target` is the object (solid particle or mesh) what the intersection is computed against.
  46474. */
  46475. SolidParticle.prototype.intersectsMesh = function (target) {
  46476. if (!this._boundingInfo || !target._boundingInfo) {
  46477. return false;
  46478. }
  46479. if (this._sps._bSphereOnly) {
  46480. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  46481. }
  46482. return this._boundingInfo.intersects(target._boundingInfo, false);
  46483. };
  46484. return SolidParticle;
  46485. }());
  46486. BABYLON.SolidParticle = SolidParticle;
  46487. var ModelShape = /** @class */ (function () {
  46488. /**
  46489. * 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.
  46490. * SPS internal tool, don't use it manually.
  46491. */
  46492. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  46493. this._indicesLength = 0; // length of the shape in the model indices array
  46494. this.shapeID = id;
  46495. this._shape = shape;
  46496. this._indicesLength = indicesLength;
  46497. this._shapeUV = shapeUV;
  46498. this._positionFunction = posFunction;
  46499. this._vertexFunction = vtxFunction;
  46500. }
  46501. return ModelShape;
  46502. }());
  46503. BABYLON.ModelShape = ModelShape;
  46504. var DepthSortedParticle = /** @class */ (function () {
  46505. function DepthSortedParticle() {
  46506. this.ind = 0; // index of the particle in the "indices" array
  46507. this.indicesLength = 0; // length of the particle shape in the "indices" array
  46508. this.sqDistance = 0.0; // squared distance from the particle to the camera
  46509. }
  46510. return DepthSortedParticle;
  46511. }());
  46512. BABYLON.DepthSortedParticle = DepthSortedParticle;
  46513. })(BABYLON || (BABYLON = {}));
  46514. //# sourceMappingURL=babylon.solidParticle.js.map
  46515. var BABYLON;
  46516. (function (BABYLON) {
  46517. /**
  46518. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  46519. */
  46520. var SolidParticleSystem = /** @class */ (function () {
  46521. /**
  46522. * Creates a SPS (Solid Particle System) object.
  46523. * `name` (String) is the SPS name, this will be the underlying mesh name.
  46524. * `scene` (Scene) is the scene in which the SPS is added.
  46525. * `updatable` (optional boolean, default true) : if the SPS must be updatable or immutable.
  46526. * `isPickable` (optional boolean, default false) : if the solid particles must be pickable.
  46527. * `enableDepthSort` (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  46528. * `particleIntersection` (optional boolean, default false) : if the solid particle intersections must be computed.
  46529. * `boundingSphereOnly` (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  46530. * `bSphereRadiusFactor` (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  46531. * Example : bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  46532. */
  46533. function SolidParticleSystem(name, scene, options) {
  46534. // public members
  46535. /**
  46536. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  46537. * Example : var p = SPS.particles[i];
  46538. */
  46539. this.particles = new Array();
  46540. /**
  46541. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  46542. */
  46543. this.nbParticles = 0;
  46544. /**
  46545. * If the particles must ever face the camera (default false). Useful for planar particles.
  46546. */
  46547. this.billboard = false;
  46548. /**
  46549. * Recompute normals when adding a shape
  46550. */
  46551. this.recomputeNormals = true;
  46552. /**
  46553. * This a counter ofr your own usage. It's not set by any SPS functions.
  46554. */
  46555. this.counter = 0;
  46556. /**
  46557. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  46558. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  46559. */
  46560. this.vars = {};
  46561. this._positions = new Array();
  46562. this._indices = new Array();
  46563. this._normals = new Array();
  46564. this._colors = new Array();
  46565. this._uvs = new Array();
  46566. this._index = 0; // indices index
  46567. this._updatable = true;
  46568. this._pickable = false;
  46569. this._isVisibilityBoxLocked = false;
  46570. this._alwaysVisible = false;
  46571. this._depthSort = false;
  46572. this._shapeCounter = 0;
  46573. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  46574. this._color = new BABYLON.Color4(0, 0, 0, 0);
  46575. this._computeParticleColor = true;
  46576. this._computeParticleTexture = true;
  46577. this._computeParticleRotation = true;
  46578. this._computeParticleVertex = false;
  46579. this._computeBoundingBox = false;
  46580. this._depthSortParticles = true;
  46581. this._cam_axisZ = BABYLON.Vector3.Zero();
  46582. this._cam_axisY = BABYLON.Vector3.Zero();
  46583. this._cam_axisX = BABYLON.Vector3.Zero();
  46584. this._axisZ = BABYLON.Axis.Z;
  46585. this._camDir = BABYLON.Vector3.Zero();
  46586. this._camInvertedPosition = BABYLON.Vector3.Zero();
  46587. this._rotMatrix = new BABYLON.Matrix();
  46588. this._invertMatrix = new BABYLON.Matrix();
  46589. this._rotated = BABYLON.Vector3.Zero();
  46590. this._quaternion = new BABYLON.Quaternion();
  46591. this._vertex = BABYLON.Vector3.Zero();
  46592. this._normal = BABYLON.Vector3.Zero();
  46593. this._yaw = 0.0;
  46594. this._pitch = 0.0;
  46595. this._roll = 0.0;
  46596. this._halfroll = 0.0;
  46597. this._halfpitch = 0.0;
  46598. this._halfyaw = 0.0;
  46599. this._sinRoll = 0.0;
  46600. this._cosRoll = 0.0;
  46601. this._sinPitch = 0.0;
  46602. this._cosPitch = 0.0;
  46603. this._sinYaw = 0.0;
  46604. this._cosYaw = 0.0;
  46605. this._mustUnrotateFixedNormals = false;
  46606. this._minimum = BABYLON.Tmp.Vector3[0];
  46607. this._maximum = BABYLON.Tmp.Vector3[1];
  46608. this._minBbox = BABYLON.Tmp.Vector3[4];
  46609. this._maxBbox = BABYLON.Tmp.Vector3[5];
  46610. this._particlesIntersect = false;
  46611. this._depthSortFunction = function (p1, p2) {
  46612. return (p2.sqDistance - p1.sqDistance);
  46613. };
  46614. this._needs32Bits = false;
  46615. this._bSphereOnly = false;
  46616. this._bSphereRadiusFactor = 1.0;
  46617. this.name = name;
  46618. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  46619. this._camera = scene.activeCamera;
  46620. this._pickable = options ? options.isPickable : false;
  46621. this._depthSort = options ? options.enableDepthSort : false;
  46622. this._particlesIntersect = options ? options.particleIntersection : false;
  46623. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  46624. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  46625. if (options && options.updatable) {
  46626. this._updatable = options.updatable;
  46627. }
  46628. else {
  46629. this._updatable = true;
  46630. }
  46631. if (this._pickable) {
  46632. this.pickedParticles = [];
  46633. }
  46634. if (this._depthSort) {
  46635. this.depthSortedParticles = [];
  46636. }
  46637. }
  46638. /**
  46639. * Builds the SPS underlying mesh. Returns a standard Mesh.
  46640. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  46641. */
  46642. SolidParticleSystem.prototype.buildMesh = function () {
  46643. if (this.nbParticles === 0) {
  46644. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  46645. this.addShape(triangle, 1);
  46646. triangle.dispose();
  46647. }
  46648. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  46649. this._positions32 = new Float32Array(this._positions);
  46650. this._uvs32 = new Float32Array(this._uvs);
  46651. this._colors32 = new Float32Array(this._colors);
  46652. if (this.recomputeNormals) {
  46653. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  46654. }
  46655. this._normals32 = new Float32Array(this._normals);
  46656. this._fixedNormal32 = new Float32Array(this._normals);
  46657. if (this._mustUnrotateFixedNormals) {
  46658. this._unrotateFixedNormals();
  46659. }
  46660. var vertexData = new BABYLON.VertexData();
  46661. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  46662. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  46663. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  46664. if (this._uvs32) {
  46665. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  46666. ;
  46667. }
  46668. if (this._colors32) {
  46669. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  46670. }
  46671. var mesh = new BABYLON.Mesh(this.name, this._scene);
  46672. vertexData.applyToMesh(mesh, this._updatable);
  46673. this.mesh = mesh;
  46674. this.mesh.isPickable = this._pickable;
  46675. // free memory
  46676. if (!this._depthSort) {
  46677. this._indices = null;
  46678. }
  46679. this._positions = null;
  46680. this._normals = null;
  46681. this._uvs = null;
  46682. this._colors = null;
  46683. if (!this._updatable) {
  46684. this.particles.length = 0;
  46685. }
  46686. return mesh;
  46687. };
  46688. /**
  46689. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  46690. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  46691. * Thus the particles generated from `digest()` have their property `position` set yet.
  46692. * `mesh` ( Mesh ) is the mesh to be digested
  46693. * `facetNb` (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  46694. * `delta` (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  46695. * `number` (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  46696. */
  46697. SolidParticleSystem.prototype.digest = function (mesh, options) {
  46698. var size = (options && options.facetNb) || 1;
  46699. var number = (options && options.number) || 0;
  46700. var delta = (options && options.delta) || 0;
  46701. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  46702. var meshInd = mesh.getIndices();
  46703. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  46704. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  46705. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  46706. var f = 0; // facet counter
  46707. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  46708. // compute size from number
  46709. if (number) {
  46710. number = (number > totalFacets) ? totalFacets : number;
  46711. size = Math.round(totalFacets / number);
  46712. delta = 0;
  46713. }
  46714. else {
  46715. size = (size > totalFacets) ? totalFacets : size;
  46716. }
  46717. var facetPos = []; // submesh positions
  46718. var facetInd = []; // submesh indices
  46719. var facetUV = []; // submesh UV
  46720. var facetCol = []; // submesh colors
  46721. var barycenter = BABYLON.Tmp.Vector3[0];
  46722. var sizeO = size;
  46723. while (f < totalFacets) {
  46724. size = sizeO + Math.floor((1 + delta) * Math.random());
  46725. if (f > totalFacets - size) {
  46726. size = totalFacets - f;
  46727. }
  46728. // reset temp arrays
  46729. facetPos.length = 0;
  46730. facetInd.length = 0;
  46731. facetUV.length = 0;
  46732. facetCol.length = 0;
  46733. // iterate over "size" facets
  46734. var fi = 0;
  46735. for (var j = f * 3; j < (f + size) * 3; j++) {
  46736. facetInd.push(fi);
  46737. var i = meshInd[j];
  46738. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  46739. if (meshUV) {
  46740. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  46741. }
  46742. if (meshCol) {
  46743. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  46744. }
  46745. fi++;
  46746. }
  46747. // create a model shape for each single particle
  46748. var idx = this.nbParticles;
  46749. var shape = this._posToShape(facetPos);
  46750. var shapeUV = this._uvsToShapeUV(facetUV);
  46751. // compute the barycenter of the shape
  46752. var v;
  46753. for (v = 0; v < shape.length; v++) {
  46754. barycenter.addInPlace(shape[v]);
  46755. }
  46756. barycenter.scaleInPlace(1 / shape.length);
  46757. // shift the shape from its barycenter to the origin
  46758. for (v = 0; v < shape.length; v++) {
  46759. shape[v].subtractInPlace(barycenter);
  46760. }
  46761. var bInfo;
  46762. if (this._particlesIntersect) {
  46763. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  46764. }
  46765. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  46766. // add the particle in the SPS
  46767. var currentPos = this._positions.length;
  46768. var currentInd = this._indices.length;
  46769. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  46770. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  46771. // initialize the particle position
  46772. this.particles[this.nbParticles].position.addInPlace(barycenter);
  46773. this._index += shape.length;
  46774. idx++;
  46775. this.nbParticles++;
  46776. this._shapeCounter++;
  46777. f += size;
  46778. }
  46779. return this;
  46780. };
  46781. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  46782. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  46783. var index = 0;
  46784. var idx = 0;
  46785. for (var p = 0; p < this.particles.length; p++) {
  46786. this._particle = this.particles[p];
  46787. this._shape = this._particle._model._shape;
  46788. if (this._particle.rotationQuaternion) {
  46789. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  46790. }
  46791. else {
  46792. this._yaw = this._particle.rotation.y;
  46793. this._pitch = this._particle.rotation.x;
  46794. this._roll = this._particle.rotation.z;
  46795. this._quaternionRotationYPR();
  46796. }
  46797. this._quaternionToRotationMatrix();
  46798. this._rotMatrix.invertToRef(this._invertMatrix);
  46799. for (var pt = 0; pt < this._shape.length; pt++) {
  46800. idx = index + pt * 3;
  46801. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  46802. this._fixedNormal32[idx] = this._normal.x;
  46803. this._fixedNormal32[idx + 1] = this._normal.y;
  46804. this._fixedNormal32[idx + 2] = this._normal.z;
  46805. }
  46806. index = idx + 3;
  46807. }
  46808. };
  46809. //reset copy
  46810. SolidParticleSystem.prototype._resetCopy = function () {
  46811. this._copy.position.x = 0;
  46812. this._copy.position.y = 0;
  46813. this._copy.position.z = 0;
  46814. this._copy.rotation.x = 0;
  46815. this._copy.rotation.y = 0;
  46816. this._copy.rotation.z = 0;
  46817. this._copy.rotationQuaternion = null;
  46818. this._copy.scaling.x = 1.0;
  46819. this._copy.scaling.y = 1.0;
  46820. this._copy.scaling.z = 1.0;
  46821. this._copy.uvs.x = 0;
  46822. this._copy.uvs.y = 0;
  46823. this._copy.uvs.z = 1.0;
  46824. this._copy.uvs.w = 1.0;
  46825. this._copy.color = null;
  46826. };
  46827. // _meshBuilder : inserts the shape model in the global SPS mesh
  46828. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  46829. var i;
  46830. var u = 0;
  46831. var c = 0;
  46832. var n = 0;
  46833. this._resetCopy();
  46834. if (options && options.positionFunction) {
  46835. options.positionFunction(this._copy, idx, idxInShape);
  46836. this._mustUnrotateFixedNormals = true;
  46837. }
  46838. if (this._copy.rotationQuaternion) {
  46839. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  46840. }
  46841. else {
  46842. this._yaw = this._copy.rotation.y;
  46843. this._pitch = this._copy.rotation.x;
  46844. this._roll = this._copy.rotation.z;
  46845. this._quaternionRotationYPR();
  46846. }
  46847. this._quaternionToRotationMatrix();
  46848. for (i = 0; i < shape.length; i++) {
  46849. this._vertex.x = shape[i].x;
  46850. this._vertex.y = shape[i].y;
  46851. this._vertex.z = shape[i].z;
  46852. if (options && options.vertexFunction) {
  46853. options.vertexFunction(this._copy, this._vertex, i);
  46854. }
  46855. this._vertex.x *= this._copy.scaling.x;
  46856. this._vertex.y *= this._copy.scaling.y;
  46857. this._vertex.z *= this._copy.scaling.z;
  46858. this._vertex.x += this._copy.pivot.x;
  46859. this._vertex.y += this._copy.pivot.y;
  46860. this._vertex.z += this._copy.pivot.z;
  46861. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  46862. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  46863. if (meshUV) {
  46864. 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);
  46865. u += 2;
  46866. }
  46867. if (this._copy.color) {
  46868. this._color = this._copy.color;
  46869. }
  46870. else if (meshCol && meshCol[c] !== undefined) {
  46871. this._color.r = meshCol[c];
  46872. this._color.g = meshCol[c + 1];
  46873. this._color.b = meshCol[c + 2];
  46874. this._color.a = meshCol[c + 3];
  46875. }
  46876. else {
  46877. this._color.r = 1.0;
  46878. this._color.g = 1.0;
  46879. this._color.b = 1.0;
  46880. this._color.a = 1.0;
  46881. }
  46882. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  46883. c += 4;
  46884. if (!this.recomputeNormals && meshNor) {
  46885. this._normal.x = meshNor[n];
  46886. this._normal.y = meshNor[n + 1];
  46887. this._normal.z = meshNor[n + 2];
  46888. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  46889. normals.push(this._normal.x, this._normal.y, this._normal.z);
  46890. n += 3;
  46891. }
  46892. }
  46893. for (i = 0; i < meshInd.length; i++) {
  46894. var current_ind = p + meshInd[i];
  46895. indices.push(current_ind);
  46896. if (current_ind > 65535) {
  46897. this._needs32Bits = true;
  46898. }
  46899. }
  46900. if (this._pickable) {
  46901. var nbfaces = meshInd.length / 3;
  46902. for (i = 0; i < nbfaces; i++) {
  46903. this.pickedParticles.push({ idx: idx, faceId: i });
  46904. }
  46905. }
  46906. if (this._depthSort) {
  46907. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  46908. }
  46909. return this._copy;
  46910. };
  46911. // returns a shape array from positions array
  46912. SolidParticleSystem.prototype._posToShape = function (positions) {
  46913. var shape = [];
  46914. for (var i = 0; i < positions.length; i += 3) {
  46915. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  46916. }
  46917. return shape;
  46918. };
  46919. // returns a shapeUV array from a Vector4 uvs
  46920. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  46921. var shapeUV = [];
  46922. if (uvs) {
  46923. for (var i = 0; i < uvs.length; i++)
  46924. shapeUV.push(uvs[i]);
  46925. }
  46926. return shapeUV;
  46927. };
  46928. // adds a new particle object in the particles array
  46929. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  46930. if (bInfo === void 0) { bInfo = null; }
  46931. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  46932. this.particles.push(sp);
  46933. return sp;
  46934. };
  46935. /**
  46936. * Adds some particles to the SPS from the model shape. Returns the shape id.
  46937. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  46938. * `mesh` is any Mesh object that will be used as a model for the solid particles.
  46939. * `nb` (positive integer) the number of particles to be created from this model
  46940. * `positionFunction` is an optional javascript function to called for each particle on SPS creation.
  46941. * `vertexFunction` is an optional javascript function to called for each vertex of each particle on SPS creation
  46942. */
  46943. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  46944. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  46945. var meshInd = mesh.getIndices();
  46946. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  46947. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  46948. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  46949. var bbInfo;
  46950. if (this._particlesIntersect) {
  46951. bbInfo = mesh.getBoundingInfo();
  46952. }
  46953. var shape = this._posToShape(meshPos);
  46954. var shapeUV = this._uvsToShapeUV(meshUV);
  46955. var posfunc = options ? options.positionFunction : null;
  46956. var vtxfunc = options ? options.vertexFunction : null;
  46957. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  46958. // particles
  46959. var sp;
  46960. var currentCopy;
  46961. var idx = this.nbParticles;
  46962. for (var i = 0; i < nb; i++) {
  46963. var currentPos = this._positions.length;
  46964. var currentInd = this._indices.length;
  46965. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  46966. if (this._updatable) {
  46967. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  46968. sp.position.copyFrom(currentCopy.position);
  46969. sp.rotation.copyFrom(currentCopy.rotation);
  46970. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  46971. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  46972. }
  46973. if (currentCopy.color && sp.color) {
  46974. sp.color.copyFrom(currentCopy.color);
  46975. }
  46976. sp.scaling.copyFrom(currentCopy.scaling);
  46977. sp.uvs.copyFrom(currentCopy.uvs);
  46978. }
  46979. this._index += shape.length;
  46980. idx++;
  46981. }
  46982. this.nbParticles += nb;
  46983. this._shapeCounter++;
  46984. return this._shapeCounter - 1;
  46985. };
  46986. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  46987. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  46988. this._resetCopy();
  46989. if (particle._model._positionFunction) {
  46990. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  46991. }
  46992. if (this._copy.rotationQuaternion) {
  46993. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  46994. }
  46995. else {
  46996. this._yaw = this._copy.rotation.y;
  46997. this._pitch = this._copy.rotation.x;
  46998. this._roll = this._copy.rotation.z;
  46999. this._quaternionRotationYPR();
  47000. }
  47001. this._quaternionToRotationMatrix();
  47002. this._shape = particle._model._shape;
  47003. for (var pt = 0; pt < this._shape.length; pt++) {
  47004. this._vertex.x = this._shape[pt].x;
  47005. this._vertex.y = this._shape[pt].y;
  47006. this._vertex.z = this._shape[pt].z;
  47007. if (particle._model._vertexFunction) {
  47008. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  47009. }
  47010. this._vertex.x *= this._copy.scaling.x;
  47011. this._vertex.y *= this._copy.scaling.y;
  47012. this._vertex.z *= this._copy.scaling.z;
  47013. this._vertex.x += this._copy.pivot.x;
  47014. this._vertex.y += this._copy.pivot.y;
  47015. this._vertex.z += this._copy.pivot.z;
  47016. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  47017. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  47018. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  47019. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  47020. }
  47021. particle.position.x = 0.0;
  47022. particle.position.y = 0.0;
  47023. particle.position.z = 0.0;
  47024. particle.rotation.x = 0.0;
  47025. particle.rotation.y = 0.0;
  47026. particle.rotation.z = 0.0;
  47027. particle.rotationQuaternion = null;
  47028. particle.scaling.x = 1.0;
  47029. particle.scaling.y = 1.0;
  47030. particle.scaling.z = 1.0;
  47031. };
  47032. /**
  47033. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  47034. * Returns the SPS.
  47035. */
  47036. SolidParticleSystem.prototype.rebuildMesh = function () {
  47037. for (var p = 0; p < this.particles.length; p++) {
  47038. this._rebuildParticle(this.particles[p]);
  47039. }
  47040. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  47041. return this;
  47042. };
  47043. /**
  47044. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  47045. * This method calls `updateParticle()` for each particle of the SPS.
  47046. * For an animated SPS, it is usually called within the render loop.
  47047. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  47048. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  47049. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  47050. * Returns the SPS.
  47051. */
  47052. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  47053. if (start === void 0) { start = 0; }
  47054. if (end === void 0) { end = this.nbParticles - 1; }
  47055. if (update === void 0) { update = true; }
  47056. if (!this._updatable) {
  47057. return this;
  47058. }
  47059. // custom beforeUpdate
  47060. this.beforeUpdateParticles(start, end, update);
  47061. this._cam_axisX.x = 1.0;
  47062. this._cam_axisX.y = 0.0;
  47063. this._cam_axisX.z = 0.0;
  47064. this._cam_axisY.x = 0.0;
  47065. this._cam_axisY.y = 1.0;
  47066. this._cam_axisY.z = 0.0;
  47067. this._cam_axisZ.x = 0.0;
  47068. this._cam_axisZ.y = 0.0;
  47069. this._cam_axisZ.z = 1.0;
  47070. // cases when the World Matrix is to be computed first
  47071. if (this.billboard || this._depthSort) {
  47072. this.mesh.computeWorldMatrix(true);
  47073. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  47074. }
  47075. // if the particles will always face the camera
  47076. if (this.billboard) {
  47077. // compute the camera position and un-rotate it by the current mesh rotation
  47078. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  47079. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  47080. this._cam_axisZ.normalize();
  47081. // same for camera up vector extracted from the cam view matrix
  47082. var view = this._camera.getViewMatrix(true);
  47083. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  47084. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  47085. this._cam_axisY.normalize();
  47086. this._cam_axisX.normalize();
  47087. }
  47088. // if depthSort, compute the camera global position in the mesh local system
  47089. if (this._depthSort) {
  47090. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  47091. }
  47092. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  47093. var idx = 0; // current position index in the global array positions32
  47094. var index = 0; // position start index in the global array positions32 of the current particle
  47095. var colidx = 0; // current color index in the global array colors32
  47096. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  47097. var uvidx = 0; // current uv index in the global array uvs32
  47098. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  47099. var pt = 0; // current index in the particle model shape
  47100. if (this.mesh.isFacetDataEnabled) {
  47101. this._computeBoundingBox = true;
  47102. }
  47103. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  47104. if (this._computeBoundingBox) {
  47105. if (start == 0 && end == this.nbParticles - 1) {
  47106. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  47107. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  47108. }
  47109. else {
  47110. if (this.mesh._boundingInfo) {
  47111. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  47112. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  47113. }
  47114. }
  47115. }
  47116. // particle loop
  47117. index = this.particles[start]._pos;
  47118. var vpos = (index / 3) | 0;
  47119. colorIndex = vpos * 4;
  47120. uvIndex = vpos * 2;
  47121. for (var p = start; p <= end; p++) {
  47122. this._particle = this.particles[p];
  47123. this._shape = this._particle._model._shape;
  47124. this._shapeUV = this._particle._model._shapeUV;
  47125. // call to custom user function to update the particle properties
  47126. this.updateParticle(this._particle);
  47127. // camera-particle distance for depth sorting
  47128. if (this._depthSort && this._depthSortParticles) {
  47129. var dsp = this.depthSortedParticles[p];
  47130. dsp.ind = this._particle._ind;
  47131. dsp.indicesLength = this._particle._model._indicesLength;
  47132. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  47133. }
  47134. // skip the computations for inactive or already invisible particles
  47135. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  47136. // increment indexes for the next particle
  47137. pt = this._shape.length;
  47138. index += pt * 3;
  47139. colorIndex += pt * 4;
  47140. uvIndex += pt * 2;
  47141. continue;
  47142. }
  47143. if (this._particle.isVisible) {
  47144. this._particle._stillInvisible = false; // un-mark permanent invisibility
  47145. // particle rotation matrix
  47146. if (this.billboard) {
  47147. this._particle.rotation.x = 0.0;
  47148. this._particle.rotation.y = 0.0;
  47149. }
  47150. if (this._computeParticleRotation || this.billboard) {
  47151. if (this._particle.rotationQuaternion) {
  47152. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  47153. }
  47154. else {
  47155. this._yaw = this._particle.rotation.y;
  47156. this._pitch = this._particle.rotation.x;
  47157. this._roll = this._particle.rotation.z;
  47158. this._quaternionRotationYPR();
  47159. }
  47160. this._quaternionToRotationMatrix();
  47161. }
  47162. // particle vertex loop
  47163. for (pt = 0; pt < this._shape.length; pt++) {
  47164. idx = index + pt * 3;
  47165. colidx = colorIndex + pt * 4;
  47166. uvidx = uvIndex + pt * 2;
  47167. this._vertex.x = this._shape[pt].x;
  47168. this._vertex.y = this._shape[pt].y;
  47169. this._vertex.z = this._shape[pt].z;
  47170. if (this._computeParticleVertex) {
  47171. this.updateParticleVertex(this._particle, this._vertex, pt);
  47172. }
  47173. // positions
  47174. this._vertex.x *= this._particle.scaling.x;
  47175. this._vertex.y *= this._particle.scaling.y;
  47176. this._vertex.z *= this._particle.scaling.z;
  47177. this._vertex.x += this._particle.pivot.x;
  47178. this._vertex.y += this._particle.pivot.y;
  47179. this._vertex.z += this._particle.pivot.z;
  47180. this._rotated.x = this._vertex.x * this._rotMatrix.m[0] + this._vertex.y * this._rotMatrix.m[4] + this._vertex.z * this._rotMatrix.m[8];
  47181. this._rotated.y = this._vertex.x * this._rotMatrix.m[1] + this._vertex.y * this._rotMatrix.m[5] + this._vertex.z * this._rotMatrix.m[9];
  47182. this._rotated.z = this._vertex.x * this._rotMatrix.m[2] + this._vertex.y * this._rotMatrix.m[6] + this._vertex.z * this._rotMatrix.m[10];
  47183. 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;
  47184. 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;
  47185. 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;
  47186. if (this._computeBoundingBox) {
  47187. if (this._positions32[idx] < this._minimum.x) {
  47188. this._minimum.x = this._positions32[idx];
  47189. }
  47190. if (this._positions32[idx] > this._maximum.x) {
  47191. this._maximum.x = this._positions32[idx];
  47192. }
  47193. if (this._positions32[idx + 1] < this._minimum.y) {
  47194. this._minimum.y = this._positions32[idx + 1];
  47195. }
  47196. if (this._positions32[idx + 1] > this._maximum.y) {
  47197. this._maximum.y = this._positions32[idx + 1];
  47198. }
  47199. if (this._positions32[idx + 2] < this._minimum.z) {
  47200. this._minimum.z = this._positions32[idx + 2];
  47201. }
  47202. if (this._positions32[idx + 2] > this._maximum.z) {
  47203. this._maximum.z = this._positions32[idx + 2];
  47204. }
  47205. }
  47206. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  47207. if (!this._computeParticleVertex) {
  47208. this._normal.x = this._fixedNormal32[idx];
  47209. this._normal.y = this._fixedNormal32[idx + 1];
  47210. this._normal.z = this._fixedNormal32[idx + 2];
  47211. this._rotated.x = this._normal.x * this._rotMatrix.m[0] + this._normal.y * this._rotMatrix.m[4] + this._normal.z * this._rotMatrix.m[8];
  47212. this._rotated.y = this._normal.x * this._rotMatrix.m[1] + this._normal.y * this._rotMatrix.m[5] + this._normal.z * this._rotMatrix.m[9];
  47213. this._rotated.z = this._normal.x * this._rotMatrix.m[2] + this._normal.y * this._rotMatrix.m[6] + this._normal.z * this._rotMatrix.m[10];
  47214. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  47215. 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;
  47216. 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;
  47217. }
  47218. if (this._computeParticleColor && this._particle.color) {
  47219. this._colors32[colidx] = this._particle.color.r;
  47220. this._colors32[colidx + 1] = this._particle.color.g;
  47221. this._colors32[colidx + 2] = this._particle.color.b;
  47222. this._colors32[colidx + 3] = this._particle.color.a;
  47223. }
  47224. if (this._computeParticleTexture) {
  47225. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  47226. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  47227. }
  47228. }
  47229. }
  47230. else {
  47231. this._particle._stillInvisible = true; // mark the particle as invisible
  47232. for (pt = 0; pt < this._shape.length; pt++) {
  47233. idx = index + pt * 3;
  47234. colidx = colorIndex + pt * 4;
  47235. uvidx = uvIndex + pt * 2;
  47236. this._positions32[idx] = 0.0;
  47237. this._positions32[idx + 1] = 0.0;
  47238. this._positions32[idx + 2] = 0.0;
  47239. this._normals32[idx] = 0.0;
  47240. this._normals32[idx + 1] = 0.0;
  47241. this._normals32[idx + 2] = 0.0;
  47242. if (this._computeParticleColor && this._particle.color) {
  47243. this._colors32[colidx] = this._particle.color.r;
  47244. this._colors32[colidx + 1] = this._particle.color.g;
  47245. this._colors32[colidx + 2] = this._particle.color.b;
  47246. this._colors32[colidx + 3] = this._particle.color.a;
  47247. }
  47248. if (this._computeParticleTexture) {
  47249. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  47250. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  47251. }
  47252. }
  47253. }
  47254. // if the particle intersections must be computed : update the bbInfo
  47255. if (this._particlesIntersect) {
  47256. var bInfo = this._particle._boundingInfo;
  47257. var bBox = bInfo.boundingBox;
  47258. var bSphere = bInfo.boundingSphere;
  47259. if (!this._bSphereOnly) {
  47260. // place, scale and rotate the particle bbox within the SPS local system, then update it
  47261. for (var b = 0; b < bBox.vectors.length; b++) {
  47262. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  47263. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  47264. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  47265. this._rotated.x = this._vertex.x * this._rotMatrix.m[0] + this._vertex.y * this._rotMatrix.m[4] + this._vertex.z * this._rotMatrix.m[8];
  47266. this._rotated.y = this._vertex.x * this._rotMatrix.m[1] + this._vertex.y * this._rotMatrix.m[5] + this._vertex.z * this._rotMatrix.m[9];
  47267. this._rotated.z = this._vertex.x * this._rotMatrix.m[2] + this._vertex.y * this._rotMatrix.m[6] + this._vertex.z * this._rotMatrix.m[10];
  47268. 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;
  47269. 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;
  47270. 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;
  47271. }
  47272. bBox._update(this.mesh._worldMatrix);
  47273. }
  47274. // place and scale the particle bouding sphere in the SPS local system, then update it
  47275. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  47276. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  47277. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  47278. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  47279. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  47280. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  47281. bSphere.center.x = this._particle.position.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  47282. bSphere.center.y = this._particle.position.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  47283. bSphere.center.z = this._particle.position.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  47284. 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));
  47285. bSphere._update(this.mesh._worldMatrix);
  47286. }
  47287. // increment indexes for the next particle
  47288. index = idx + 3;
  47289. colorIndex = colidx + 4;
  47290. uvIndex = uvidx + 2;
  47291. }
  47292. // if the VBO must be updated
  47293. if (update) {
  47294. if (this._computeParticleColor) {
  47295. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  47296. }
  47297. if (this._computeParticleTexture) {
  47298. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  47299. }
  47300. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  47301. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  47302. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  47303. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  47304. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  47305. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32, params);
  47306. for (var i = 0; i < this._normals32.length; i++) {
  47307. this._fixedNormal32[i] = this._normals32[i];
  47308. }
  47309. }
  47310. if (!this.mesh.areNormalsFrozen) {
  47311. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  47312. }
  47313. }
  47314. if (this._depthSort && this._depthSortParticles) {
  47315. this.depthSortedParticles.sort(this._depthSortFunction);
  47316. var dspl = this.depthSortedParticles.length;
  47317. var sorted = 0;
  47318. var lind = 0;
  47319. var sind = 0;
  47320. var sid = 0;
  47321. for (sorted = 0; sorted < dspl; sorted++) {
  47322. lind = this.depthSortedParticles[sorted].indicesLength;
  47323. sind = this.depthSortedParticles[sorted].ind;
  47324. for (var i = 0; i < lind; i++) {
  47325. this._indices32[sid] = this._indices[sind + i];
  47326. sid++;
  47327. }
  47328. }
  47329. this.mesh.updateIndices(this._indices32);
  47330. }
  47331. }
  47332. if (this._computeBoundingBox) {
  47333. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  47334. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  47335. }
  47336. this.afterUpdateParticles(start, end, update);
  47337. return this;
  47338. };
  47339. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  47340. this._halfroll = this._roll * 0.5;
  47341. this._halfpitch = this._pitch * 0.5;
  47342. this._halfyaw = this._yaw * 0.5;
  47343. this._sinRoll = Math.sin(this._halfroll);
  47344. this._cosRoll = Math.cos(this._halfroll);
  47345. this._sinPitch = Math.sin(this._halfpitch);
  47346. this._cosPitch = Math.cos(this._halfpitch);
  47347. this._sinYaw = Math.sin(this._halfyaw);
  47348. this._cosYaw = Math.cos(this._halfyaw);
  47349. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  47350. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  47351. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  47352. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  47353. };
  47354. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  47355. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  47356. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  47357. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  47358. this._rotMatrix.m[3] = 0;
  47359. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  47360. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  47361. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  47362. this._rotMatrix.m[7] = 0;
  47363. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  47364. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  47365. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  47366. this._rotMatrix.m[11] = 0;
  47367. this._rotMatrix.m[12] = 0;
  47368. this._rotMatrix.m[13] = 0;
  47369. this._rotMatrix.m[14] = 0;
  47370. this._rotMatrix.m[15] = 1.0;
  47371. };
  47372. /**
  47373. * Disposes the SPS.
  47374. * Returns nothing.
  47375. */
  47376. SolidParticleSystem.prototype.dispose = function () {
  47377. this.mesh.dispose();
  47378. this.vars = null;
  47379. // drop references to internal big arrays for the GC
  47380. this._positions = null;
  47381. this._indices = null;
  47382. this._normals = null;
  47383. this._uvs = null;
  47384. this._colors = null;
  47385. this._indices32 = null;
  47386. this._positions32 = null;
  47387. this._normals32 = null;
  47388. this._fixedNormal32 = null;
  47389. this._uvs32 = null;
  47390. this._colors32 = null;
  47391. this.pickedParticles = null;
  47392. };
  47393. /**
  47394. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  47395. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  47396. * Returns the SPS.
  47397. */
  47398. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  47399. if (!this._isVisibilityBoxLocked) {
  47400. this.mesh.refreshBoundingInfo();
  47401. }
  47402. return this;
  47403. };
  47404. /**
  47405. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  47406. * @param size the size (float) of the visibility box
  47407. * note : this doesn't lock the SPS mesh bounding box.
  47408. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  47409. */
  47410. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  47411. var vis = size / 2;
  47412. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  47413. };
  47414. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  47415. // getter and setter
  47416. get: function () {
  47417. return this._alwaysVisible;
  47418. },
  47419. /**
  47420. * Sets the SPS as always visible or not
  47421. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  47422. */
  47423. set: function (val) {
  47424. this._alwaysVisible = val;
  47425. this.mesh.alwaysSelectAsActiveMesh = val;
  47426. },
  47427. enumerable: true,
  47428. configurable: true
  47429. });
  47430. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  47431. get: function () {
  47432. return this._isVisibilityBoxLocked;
  47433. },
  47434. /**
  47435. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  47436. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  47437. */
  47438. set: function (val) {
  47439. this._isVisibilityBoxLocked = val;
  47440. var boundingInfo = this.mesh.getBoundingInfo();
  47441. boundingInfo.isLocked = val;
  47442. },
  47443. enumerable: true,
  47444. configurable: true
  47445. });
  47446. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  47447. // getters
  47448. get: function () {
  47449. return this._computeParticleRotation;
  47450. },
  47451. // Optimizer setters
  47452. /**
  47453. * Tells to `setParticles()` to compute the particle rotations or not.
  47454. * Default value : true. The SPS is faster when it's set to false.
  47455. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  47456. */
  47457. set: function (val) {
  47458. this._computeParticleRotation = val;
  47459. },
  47460. enumerable: true,
  47461. configurable: true
  47462. });
  47463. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  47464. get: function () {
  47465. return this._computeParticleColor;
  47466. },
  47467. /**
  47468. * Tells to `setParticles()` to compute the particle colors or not.
  47469. * Default value : true. The SPS is faster when it's set to false.
  47470. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  47471. */
  47472. set: function (val) {
  47473. this._computeParticleColor = val;
  47474. },
  47475. enumerable: true,
  47476. configurable: true
  47477. });
  47478. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  47479. get: function () {
  47480. return this._computeParticleTexture;
  47481. },
  47482. /**
  47483. * Tells to `setParticles()` to compute the particle textures or not.
  47484. * Default value : true. The SPS is faster when it's set to false.
  47485. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  47486. */
  47487. set: function (val) {
  47488. this._computeParticleTexture = val;
  47489. },
  47490. enumerable: true,
  47491. configurable: true
  47492. });
  47493. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  47494. get: function () {
  47495. return this._computeParticleVertex;
  47496. },
  47497. /**
  47498. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  47499. * Default value : false. The SPS is faster when it's set to false.
  47500. * Note : the particle custom vertex positions aren't stored values.
  47501. */
  47502. set: function (val) {
  47503. this._computeParticleVertex = val;
  47504. },
  47505. enumerable: true,
  47506. configurable: true
  47507. });
  47508. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  47509. get: function () {
  47510. return this._computeBoundingBox;
  47511. },
  47512. /**
  47513. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  47514. */
  47515. set: function (val) {
  47516. this._computeBoundingBox = val;
  47517. },
  47518. enumerable: true,
  47519. configurable: true
  47520. });
  47521. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  47522. get: function () {
  47523. return this._depthSortParticles;
  47524. },
  47525. /**
  47526. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  47527. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  47528. * Default : `true`
  47529. */
  47530. set: function (val) {
  47531. this._depthSortParticles = val;
  47532. },
  47533. enumerable: true,
  47534. configurable: true
  47535. });
  47536. // =======================================================================
  47537. // Particle behavior logic
  47538. // these following methods may be overwritten by the user to fit his needs
  47539. /**
  47540. * This function does nothing. It may be overwritten to set all the particle first values.
  47541. * The SPS doesn't call this function, you may have to call it by your own.
  47542. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  47543. */
  47544. SolidParticleSystem.prototype.initParticles = function () {
  47545. };
  47546. /**
  47547. * This function does nothing. It may be overwritten to recycle a particle.
  47548. * The SPS doesn't call this function, you may have to call it by your own.
  47549. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  47550. */
  47551. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  47552. return particle;
  47553. };
  47554. /**
  47555. * Updates a particle : this function should be overwritten by the user.
  47556. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  47557. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  47558. * ex : just set a particle position or velocity and recycle conditions
  47559. */
  47560. SolidParticleSystem.prototype.updateParticle = function (particle) {
  47561. return particle;
  47562. };
  47563. /**
  47564. * Updates a vertex of a particle : it can be overwritten by the user.
  47565. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  47566. * @param particle the current particle
  47567. * @param vertex the current index of the current particle
  47568. * @param pt the index of the current vertex in the particle shape
  47569. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  47570. * ex : just set a vertex particle position
  47571. */
  47572. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  47573. return vertex;
  47574. };
  47575. /**
  47576. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  47577. * This does nothing and may be overwritten by the user.
  47578. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  47579. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  47580. * @param update the boolean update value actually passed to setParticles()
  47581. */
  47582. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  47583. };
  47584. /**
  47585. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  47586. * This will be passed three parameters.
  47587. * This does nothing and may be overwritten by the user.
  47588. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  47589. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  47590. * @param update the boolean update value actually passed to setParticles()
  47591. */
  47592. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  47593. };
  47594. return SolidParticleSystem;
  47595. }());
  47596. BABYLON.SolidParticleSystem = SolidParticleSystem;
  47597. })(BABYLON || (BABYLON = {}));
  47598. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  47599. var BABYLON;
  47600. (function (BABYLON) {
  47601. var GroundMesh = /** @class */ (function (_super) {
  47602. __extends(GroundMesh, _super);
  47603. function GroundMesh(name, scene) {
  47604. var _this = _super.call(this, name, scene) || this;
  47605. _this.generateOctree = false;
  47606. return _this;
  47607. }
  47608. GroundMesh.prototype.getClassName = function () {
  47609. return "GroundMesh";
  47610. };
  47611. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  47612. get: function () {
  47613. return Math.min(this._subdivisionsX, this._subdivisionsY);
  47614. },
  47615. enumerable: true,
  47616. configurable: true
  47617. });
  47618. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  47619. get: function () {
  47620. return this._subdivisionsX;
  47621. },
  47622. enumerable: true,
  47623. configurable: true
  47624. });
  47625. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  47626. get: function () {
  47627. return this._subdivisionsY;
  47628. },
  47629. enumerable: true,
  47630. configurable: true
  47631. });
  47632. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  47633. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  47634. this._subdivisionsX = chunksCount;
  47635. this._subdivisionsY = chunksCount;
  47636. this.subdivide(chunksCount);
  47637. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  47638. };
  47639. /**
  47640. * Returns a height (y) value in the Worl system :
  47641. * the ground altitude at the coordinates (x, z) expressed in the World system.
  47642. * Returns the ground y position if (x, z) are outside the ground surface.
  47643. */
  47644. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  47645. var world = this.getWorldMatrix();
  47646. var invMat = BABYLON.Tmp.Matrix[5];
  47647. world.invertToRef(invMat);
  47648. var tmpVect = BABYLON.Tmp.Vector3[8];
  47649. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  47650. x = tmpVect.x;
  47651. z = tmpVect.z;
  47652. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  47653. return this.position.y;
  47654. }
  47655. if (!this._heightQuads || this._heightQuads.length == 0) {
  47656. this._initHeightQuads();
  47657. this._computeHeightQuads();
  47658. }
  47659. var facet = this._getFacetAt(x, z);
  47660. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  47661. // return y in the World system
  47662. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  47663. return tmpVect.y;
  47664. };
  47665. /**
  47666. * Returns a normalized vector (Vector3) orthogonal to the ground
  47667. * at the ground coordinates (x, z) expressed in the World system.
  47668. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  47669. */
  47670. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  47671. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  47672. this.getNormalAtCoordinatesToRef(x, z, normal);
  47673. return normal;
  47674. };
  47675. /**
  47676. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  47677. * at the ground coordinates (x, z) expressed in the World system.
  47678. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  47679. * Returns the GroundMesh.
  47680. */
  47681. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  47682. var world = this.getWorldMatrix();
  47683. var tmpMat = BABYLON.Tmp.Matrix[5];
  47684. world.invertToRef(tmpMat);
  47685. var tmpVect = BABYLON.Tmp.Vector3[8];
  47686. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  47687. x = tmpVect.x;
  47688. z = tmpVect.z;
  47689. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  47690. return this;
  47691. }
  47692. if (!this._heightQuads || this._heightQuads.length == 0) {
  47693. this._initHeightQuads();
  47694. this._computeHeightQuads();
  47695. }
  47696. var facet = this._getFacetAt(x, z);
  47697. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  47698. return this;
  47699. };
  47700. /**
  47701. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  47702. * if the ground has been updated.
  47703. * This can be used in the render loop.
  47704. * Returns the GroundMesh.
  47705. */
  47706. GroundMesh.prototype.updateCoordinateHeights = function () {
  47707. if (!this._heightQuads || this._heightQuads.length == 0) {
  47708. this._initHeightQuads();
  47709. }
  47710. this._computeHeightQuads();
  47711. return this;
  47712. };
  47713. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  47714. GroundMesh.prototype._getFacetAt = function (x, z) {
  47715. // retrieve col and row from x, z coordinates in the ground local system
  47716. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  47717. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  47718. var quad = this._heightQuads[row * this._subdivisionsX + col];
  47719. var facet;
  47720. if (z < quad.slope.x * x + quad.slope.y) {
  47721. facet = quad.facet1;
  47722. }
  47723. else {
  47724. facet = quad.facet2;
  47725. }
  47726. return facet;
  47727. };
  47728. // Creates and populates the heightMap array with "facet" elements :
  47729. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  47730. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  47731. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  47732. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  47733. // Returns the GroundMesh.
  47734. GroundMesh.prototype._initHeightQuads = function () {
  47735. var subdivisionsX = this._subdivisionsX;
  47736. var subdivisionsY = this._subdivisionsY;
  47737. this._heightQuads = new Array();
  47738. for (var row = 0; row < subdivisionsY; row++) {
  47739. for (var col = 0; col < subdivisionsX; col++) {
  47740. 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) };
  47741. this._heightQuads[row * subdivisionsX + col] = quad;
  47742. }
  47743. }
  47744. return this;
  47745. };
  47746. // Compute each quad element values and update the the heightMap array :
  47747. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  47748. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  47749. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  47750. // Returns the GroundMesh.
  47751. GroundMesh.prototype._computeHeightQuads = function () {
  47752. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  47753. if (!positions) {
  47754. return this;
  47755. }
  47756. var v1 = BABYLON.Tmp.Vector3[3];
  47757. var v2 = BABYLON.Tmp.Vector3[2];
  47758. var v3 = BABYLON.Tmp.Vector3[1];
  47759. var v4 = BABYLON.Tmp.Vector3[0];
  47760. var v1v2 = BABYLON.Tmp.Vector3[4];
  47761. var v1v3 = BABYLON.Tmp.Vector3[5];
  47762. var v1v4 = BABYLON.Tmp.Vector3[6];
  47763. var norm1 = BABYLON.Tmp.Vector3[7];
  47764. var norm2 = BABYLON.Tmp.Vector3[8];
  47765. var i = 0;
  47766. var j = 0;
  47767. var k = 0;
  47768. var cd = 0; // 2D slope coefficient : z = cd * x + h
  47769. var h = 0;
  47770. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  47771. var d2 = 0;
  47772. var subdivisionsX = this._subdivisionsX;
  47773. var subdivisionsY = this._subdivisionsY;
  47774. for (var row = 0; row < subdivisionsY; row++) {
  47775. for (var col = 0; col < subdivisionsX; col++) {
  47776. i = col * 3;
  47777. j = row * (subdivisionsX + 1) * 3;
  47778. k = (row + 1) * (subdivisionsX + 1) * 3;
  47779. v1.x = positions[j + i];
  47780. v1.y = positions[j + i + 1];
  47781. v1.z = positions[j + i + 2];
  47782. v2.x = positions[j + i + 3];
  47783. v2.y = positions[j + i + 4];
  47784. v2.z = positions[j + i + 5];
  47785. v3.x = positions[k + i];
  47786. v3.y = positions[k + i + 1];
  47787. v3.z = positions[k + i + 2];
  47788. v4.x = positions[k + i + 3];
  47789. v4.y = positions[k + i + 4];
  47790. v4.z = positions[k + i + 5];
  47791. // 2D slope V1V4
  47792. cd = (v4.z - v1.z) / (v4.x - v1.x);
  47793. h = v1.z - cd * v1.x; // v1 belongs to the slope
  47794. // facet equations :
  47795. // we compute each facet normal vector
  47796. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  47797. // we compute the value d by applying the equation to v1 which belongs to the plane
  47798. // then we store the facet equation in a Vector4
  47799. v2.subtractToRef(v1, v1v2);
  47800. v3.subtractToRef(v1, v1v3);
  47801. v4.subtractToRef(v1, v1v4);
  47802. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  47803. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  47804. norm1.normalize();
  47805. norm2.normalize();
  47806. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  47807. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  47808. var quad = this._heightQuads[row * subdivisionsX + col];
  47809. quad.slope.copyFromFloats(cd, h);
  47810. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  47811. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  47812. }
  47813. }
  47814. return this;
  47815. };
  47816. GroundMesh.prototype.serialize = function (serializationObject) {
  47817. _super.prototype.serialize.call(this, serializationObject);
  47818. serializationObject.subdivisionsX = this._subdivisionsX;
  47819. serializationObject.subdivisionsY = this._subdivisionsY;
  47820. serializationObject.minX = this._minX;
  47821. serializationObject.maxX = this._maxX;
  47822. serializationObject.minZ = this._minZ;
  47823. serializationObject.maxZ = this._maxZ;
  47824. serializationObject.width = this._width;
  47825. serializationObject.height = this._height;
  47826. };
  47827. GroundMesh.Parse = function (parsedMesh, scene) {
  47828. var result = new GroundMesh(parsedMesh.name, scene);
  47829. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  47830. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  47831. result._minX = parsedMesh.minX;
  47832. result._maxX = parsedMesh.maxX;
  47833. result._minZ = parsedMesh.minZ;
  47834. result._maxZ = parsedMesh.maxZ;
  47835. result._width = parsedMesh.width;
  47836. result._height = parsedMesh.height;
  47837. return result;
  47838. };
  47839. return GroundMesh;
  47840. }(BABYLON.Mesh));
  47841. BABYLON.GroundMesh = GroundMesh;
  47842. })(BABYLON || (BABYLON = {}));
  47843. //# sourceMappingURL=babylon.groundMesh.js.map
  47844. var BABYLON;
  47845. (function (BABYLON) {
  47846. /**
  47847. * Creates an instance based on a source mesh.
  47848. */
  47849. var InstancedMesh = /** @class */ (function (_super) {
  47850. __extends(InstancedMesh, _super);
  47851. function InstancedMesh(name, source) {
  47852. var _this = _super.call(this, name, source.getScene()) || this;
  47853. source.instances.push(_this);
  47854. _this._sourceMesh = source;
  47855. _this.position.copyFrom(source.position);
  47856. _this.rotation.copyFrom(source.rotation);
  47857. _this.scaling.copyFrom(source.scaling);
  47858. if (source.rotationQuaternion) {
  47859. _this.rotationQuaternion = source.rotationQuaternion.clone();
  47860. }
  47861. _this.infiniteDistance = source.infiniteDistance;
  47862. _this.setPivotMatrix(source.getPivotMatrix());
  47863. _this.refreshBoundingInfo();
  47864. _this._syncSubMeshes();
  47865. return _this;
  47866. }
  47867. /**
  47868. * Returns the string "InstancedMesh".
  47869. */
  47870. InstancedMesh.prototype.getClassName = function () {
  47871. return "InstancedMesh";
  47872. };
  47873. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  47874. // Methods
  47875. get: function () {
  47876. return this._sourceMesh.receiveShadows;
  47877. },
  47878. enumerable: true,
  47879. configurable: true
  47880. });
  47881. Object.defineProperty(InstancedMesh.prototype, "material", {
  47882. get: function () {
  47883. return this._sourceMesh.material;
  47884. },
  47885. enumerable: true,
  47886. configurable: true
  47887. });
  47888. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  47889. get: function () {
  47890. return this._sourceMesh.visibility;
  47891. },
  47892. enumerable: true,
  47893. configurable: true
  47894. });
  47895. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  47896. get: function () {
  47897. return this._sourceMesh.skeleton;
  47898. },
  47899. enumerable: true,
  47900. configurable: true
  47901. });
  47902. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  47903. get: function () {
  47904. return this._sourceMesh.renderingGroupId;
  47905. },
  47906. enumerable: true,
  47907. configurable: true
  47908. });
  47909. /**
  47910. * Returns the total number of vertices (integer).
  47911. */
  47912. InstancedMesh.prototype.getTotalVertices = function () {
  47913. return this._sourceMesh.getTotalVertices();
  47914. };
  47915. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  47916. get: function () {
  47917. return this._sourceMesh;
  47918. },
  47919. enumerable: true,
  47920. configurable: true
  47921. });
  47922. /**
  47923. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  47924. */
  47925. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  47926. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  47927. };
  47928. /**
  47929. * Sets the vertex data of the mesh geometry for the requested `kind`.
  47930. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  47931. * The `data` are either a numeric array either a Float32Array.
  47932. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  47933. * 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).
  47934. * Note that a new underlying VertexBuffer object is created each call.
  47935. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  47936. *
  47937. * Possible `kind` values :
  47938. * - BABYLON.VertexBuffer.PositionKind
  47939. * - BABYLON.VertexBuffer.UVKind
  47940. * - BABYLON.VertexBuffer.UV2Kind
  47941. * - BABYLON.VertexBuffer.UV3Kind
  47942. * - BABYLON.VertexBuffer.UV4Kind
  47943. * - BABYLON.VertexBuffer.UV5Kind
  47944. * - BABYLON.VertexBuffer.UV6Kind
  47945. * - BABYLON.VertexBuffer.ColorKind
  47946. * - BABYLON.VertexBuffer.MatricesIndicesKind
  47947. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  47948. * - BABYLON.VertexBuffer.MatricesWeightsKind
  47949. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  47950. *
  47951. * Returns the Mesh.
  47952. */
  47953. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  47954. if (this.sourceMesh) {
  47955. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  47956. }
  47957. return this.sourceMesh;
  47958. };
  47959. /**
  47960. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  47961. * If the mesh has no geometry, it is simply returned as it is.
  47962. * The `data` are either a numeric array either a Float32Array.
  47963. * No new underlying VertexBuffer object is created.
  47964. * 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.
  47965. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  47966. *
  47967. * Possible `kind` values :
  47968. * - BABYLON.VertexBuffer.PositionKind
  47969. * - BABYLON.VertexBuffer.UVKind
  47970. * - BABYLON.VertexBuffer.UV2Kind
  47971. * - BABYLON.VertexBuffer.UV3Kind
  47972. * - BABYLON.VertexBuffer.UV4Kind
  47973. * - BABYLON.VertexBuffer.UV5Kind
  47974. * - BABYLON.VertexBuffer.UV6Kind
  47975. * - BABYLON.VertexBuffer.ColorKind
  47976. * - BABYLON.VertexBuffer.MatricesIndicesKind
  47977. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  47978. * - BABYLON.VertexBuffer.MatricesWeightsKind
  47979. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  47980. *
  47981. * Returns the Mesh.
  47982. */
  47983. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  47984. if (this.sourceMesh) {
  47985. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  47986. }
  47987. return this.sourceMesh;
  47988. };
  47989. /**
  47990. * Sets the mesh indices.
  47991. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  47992. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  47993. * This method creates a new index buffer each call.
  47994. * Returns the Mesh.
  47995. */
  47996. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  47997. if (totalVertices === void 0) { totalVertices = null; }
  47998. if (this.sourceMesh) {
  47999. this.sourceMesh.setIndices(indices, totalVertices);
  48000. }
  48001. return this.sourceMesh;
  48002. };
  48003. /**
  48004. * Boolean : True if the mesh owns the requested kind of data.
  48005. */
  48006. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  48007. return this._sourceMesh.isVerticesDataPresent(kind);
  48008. };
  48009. /**
  48010. * Returns an array of indices (IndicesArray).
  48011. */
  48012. InstancedMesh.prototype.getIndices = function () {
  48013. return this._sourceMesh.getIndices();
  48014. };
  48015. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  48016. get: function () {
  48017. return this._sourceMesh._positions;
  48018. },
  48019. enumerable: true,
  48020. configurable: true
  48021. });
  48022. /**
  48023. * Sets a new updated BoundingInfo to the mesh.
  48024. * Returns the mesh.
  48025. */
  48026. InstancedMesh.prototype.refreshBoundingInfo = function () {
  48027. var meshBB = this._sourceMesh.getBoundingInfo();
  48028. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  48029. this._updateBoundingInfo();
  48030. return this;
  48031. };
  48032. InstancedMesh.prototype._preActivate = function () {
  48033. if (this._currentLOD) {
  48034. this._currentLOD._preActivate();
  48035. }
  48036. return this;
  48037. };
  48038. InstancedMesh.prototype._activate = function (renderId) {
  48039. if (this._currentLOD) {
  48040. this._currentLOD._registerInstanceForRenderId(this, renderId);
  48041. }
  48042. return this;
  48043. };
  48044. /**
  48045. * Returns the current associated LOD AbstractMesh.
  48046. */
  48047. InstancedMesh.prototype.getLOD = function (camera) {
  48048. if (!camera) {
  48049. return this;
  48050. }
  48051. var boundingInfo = this.getBoundingInfo();
  48052. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  48053. if (this._currentLOD === this.sourceMesh) {
  48054. return this;
  48055. }
  48056. return this._currentLOD;
  48057. };
  48058. InstancedMesh.prototype._syncSubMeshes = function () {
  48059. this.releaseSubMeshes();
  48060. if (this._sourceMesh.subMeshes) {
  48061. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  48062. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  48063. }
  48064. }
  48065. return this;
  48066. };
  48067. InstancedMesh.prototype._generatePointsArray = function () {
  48068. return this._sourceMesh._generatePointsArray();
  48069. };
  48070. /**
  48071. * Creates a new InstancedMesh from the current mesh.
  48072. * - name (string) : the cloned mesh name
  48073. * - newParent (optional Node) : the optional Node to parent the clone to.
  48074. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  48075. *
  48076. * Returns the clone.
  48077. */
  48078. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  48079. var result = this._sourceMesh.createInstance(name);
  48080. // Deep copy
  48081. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  48082. // Bounding info
  48083. this.refreshBoundingInfo();
  48084. // Parent
  48085. if (newParent) {
  48086. result.parent = newParent;
  48087. }
  48088. if (!doNotCloneChildren) {
  48089. // Children
  48090. for (var index = 0; index < this.getScene().meshes.length; index++) {
  48091. var mesh = this.getScene().meshes[index];
  48092. if (mesh.parent === this) {
  48093. mesh.clone(mesh.name, result);
  48094. }
  48095. }
  48096. }
  48097. result.computeWorldMatrix(true);
  48098. return result;
  48099. };
  48100. /**
  48101. * Disposes the InstancedMesh.
  48102. * Returns nothing.
  48103. */
  48104. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  48105. // Remove from mesh
  48106. var index = this._sourceMesh.instances.indexOf(this);
  48107. this._sourceMesh.instances.splice(index, 1);
  48108. _super.prototype.dispose.call(this, doNotRecurse);
  48109. };
  48110. return InstancedMesh;
  48111. }(BABYLON.AbstractMesh));
  48112. BABYLON.InstancedMesh = InstancedMesh;
  48113. })(BABYLON || (BABYLON = {}));
  48114. //# sourceMappingURL=babylon.instancedMesh.js.map
  48115. var BABYLON;
  48116. (function (BABYLON) {
  48117. var LinesMesh = /** @class */ (function (_super) {
  48118. __extends(LinesMesh, _super);
  48119. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  48120. if (scene === void 0) { scene = null; }
  48121. if (parent === void 0) { parent = null; }
  48122. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  48123. _this.useVertexColor = useVertexColor;
  48124. _this.useVertexAlpha = useVertexAlpha;
  48125. _this.color = new BABYLON.Color3(1, 1, 1);
  48126. _this.alpha = 1;
  48127. if (source) {
  48128. _this.color = source.color.clone();
  48129. _this.alpha = source.alpha;
  48130. _this.useVertexColor = source.useVertexColor;
  48131. _this.useVertexAlpha = source.useVertexAlpha;
  48132. }
  48133. _this._intersectionThreshold = 0.1;
  48134. var defines = [];
  48135. var options = {
  48136. attributes: [BABYLON.VertexBuffer.PositionKind],
  48137. uniforms: ["world", "viewProjection"],
  48138. needAlphaBlending: true,
  48139. defines: defines
  48140. };
  48141. if (useVertexAlpha === false) {
  48142. options.needAlphaBlending = false;
  48143. }
  48144. if (!useVertexColor) {
  48145. options.uniforms.push("color");
  48146. }
  48147. else {
  48148. options.defines.push("#define VERTEXCOLOR");
  48149. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  48150. }
  48151. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  48152. return _this;
  48153. }
  48154. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  48155. /**
  48156. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  48157. * This margin is expressed in world space coordinates, so its value may vary.
  48158. * Default value is 0.1
  48159. * @returns the intersection Threshold value.
  48160. */
  48161. get: function () {
  48162. return this._intersectionThreshold;
  48163. },
  48164. /**
  48165. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  48166. * This margin is expressed in world space coordinates, so its value may vary.
  48167. * @param value the new threshold to apply
  48168. */
  48169. set: function (value) {
  48170. if (this._intersectionThreshold === value) {
  48171. return;
  48172. }
  48173. this._intersectionThreshold = value;
  48174. if (this.geometry) {
  48175. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  48176. }
  48177. },
  48178. enumerable: true,
  48179. configurable: true
  48180. });
  48181. /**
  48182. * Returns the string "LineMesh"
  48183. */
  48184. LinesMesh.prototype.getClassName = function () {
  48185. return "LinesMesh";
  48186. };
  48187. Object.defineProperty(LinesMesh.prototype, "material", {
  48188. get: function () {
  48189. return this._colorShader;
  48190. },
  48191. set: function (value) {
  48192. // Do nothing
  48193. },
  48194. enumerable: true,
  48195. configurable: true
  48196. });
  48197. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  48198. get: function () {
  48199. return false;
  48200. },
  48201. enumerable: true,
  48202. configurable: true
  48203. });
  48204. LinesMesh.prototype.createInstance = function (name) {
  48205. throw new Error("LinesMeshes do not support createInstance.");
  48206. };
  48207. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  48208. if (!this._geometry) {
  48209. return this;
  48210. }
  48211. // VBOs
  48212. this._geometry._bind(this._colorShader.getEffect());
  48213. // Color
  48214. if (!this.useVertexColor) {
  48215. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  48216. }
  48217. return this;
  48218. };
  48219. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  48220. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  48221. return this;
  48222. }
  48223. var engine = this.getScene().getEngine();
  48224. // Draw order
  48225. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  48226. return this;
  48227. };
  48228. LinesMesh.prototype.dispose = function (doNotRecurse) {
  48229. this._colorShader.dispose();
  48230. _super.prototype.dispose.call(this, doNotRecurse);
  48231. };
  48232. /**
  48233. * Returns a new LineMesh object cloned from the current one.
  48234. */
  48235. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  48236. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  48237. };
  48238. return LinesMesh;
  48239. }(BABYLON.Mesh));
  48240. BABYLON.LinesMesh = LinesMesh;
  48241. })(BABYLON || (BABYLON = {}));
  48242. //# sourceMappingURL=babylon.linesMesh.js.map
  48243. var BABYLON;
  48244. (function (BABYLON) {
  48245. var ShaderMaterial = /** @class */ (function (_super) {
  48246. __extends(ShaderMaterial, _super);
  48247. function ShaderMaterial(name, scene, shaderPath, options) {
  48248. var _this = _super.call(this, name, scene) || this;
  48249. _this._textures = {};
  48250. _this._textureArrays = {};
  48251. _this._floats = {};
  48252. _this._ints = {};
  48253. _this._floatsArrays = {};
  48254. _this._colors3 = {};
  48255. _this._colors3Arrays = {};
  48256. _this._colors4 = {};
  48257. _this._vectors2 = {};
  48258. _this._vectors3 = {};
  48259. _this._vectors4 = {};
  48260. _this._matrices = {};
  48261. _this._matrices3x3 = {};
  48262. _this._matrices2x2 = {};
  48263. _this._vectors2Arrays = {};
  48264. _this._vectors3Arrays = {};
  48265. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  48266. _this._shaderPath = shaderPath;
  48267. options.needAlphaBlending = options.needAlphaBlending || false;
  48268. options.needAlphaTesting = options.needAlphaTesting || false;
  48269. options.attributes = options.attributes || ["position", "normal", "uv"];
  48270. options.uniforms = options.uniforms || ["worldViewProjection"];
  48271. options.uniformBuffers = options.uniformBuffers || [];
  48272. options.samplers = options.samplers || [];
  48273. options.defines = options.defines || [];
  48274. _this._options = options;
  48275. return _this;
  48276. }
  48277. ShaderMaterial.prototype.getClassName = function () {
  48278. return "ShaderMaterial";
  48279. };
  48280. ShaderMaterial.prototype.needAlphaBlending = function () {
  48281. return this._options.needAlphaBlending;
  48282. };
  48283. ShaderMaterial.prototype.needAlphaTesting = function () {
  48284. return this._options.needAlphaTesting;
  48285. };
  48286. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  48287. if (this._options.uniforms.indexOf(uniformName) === -1) {
  48288. this._options.uniforms.push(uniformName);
  48289. }
  48290. };
  48291. ShaderMaterial.prototype.setTexture = function (name, texture) {
  48292. if (this._options.samplers.indexOf(name) === -1) {
  48293. this._options.samplers.push(name);
  48294. }
  48295. this._textures[name] = texture;
  48296. return this;
  48297. };
  48298. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  48299. if (this._options.samplers.indexOf(name) === -1) {
  48300. this._options.samplers.push(name);
  48301. }
  48302. this._checkUniform(name);
  48303. this._textureArrays[name] = textures;
  48304. return this;
  48305. };
  48306. ShaderMaterial.prototype.setFloat = function (name, value) {
  48307. this._checkUniform(name);
  48308. this._floats[name] = value;
  48309. return this;
  48310. };
  48311. ShaderMaterial.prototype.setInt = function (name, value) {
  48312. this._checkUniform(name);
  48313. this._ints[name] = value;
  48314. return this;
  48315. };
  48316. ShaderMaterial.prototype.setFloats = function (name, value) {
  48317. this._checkUniform(name);
  48318. this._floatsArrays[name] = value;
  48319. return this;
  48320. };
  48321. ShaderMaterial.prototype.setColor3 = function (name, value) {
  48322. this._checkUniform(name);
  48323. this._colors3[name] = value;
  48324. return this;
  48325. };
  48326. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  48327. this._checkUniform(name);
  48328. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  48329. color.toArray(arr, arr.length);
  48330. return arr;
  48331. }, []);
  48332. return this;
  48333. };
  48334. ShaderMaterial.prototype.setColor4 = function (name, value) {
  48335. this._checkUniform(name);
  48336. this._colors4[name] = value;
  48337. return this;
  48338. };
  48339. ShaderMaterial.prototype.setVector2 = function (name, value) {
  48340. this._checkUniform(name);
  48341. this._vectors2[name] = value;
  48342. return this;
  48343. };
  48344. ShaderMaterial.prototype.setVector3 = function (name, value) {
  48345. this._checkUniform(name);
  48346. this._vectors3[name] = value;
  48347. return this;
  48348. };
  48349. ShaderMaterial.prototype.setVector4 = function (name, value) {
  48350. this._checkUniform(name);
  48351. this._vectors4[name] = value;
  48352. return this;
  48353. };
  48354. ShaderMaterial.prototype.setMatrix = function (name, value) {
  48355. this._checkUniform(name);
  48356. this._matrices[name] = value;
  48357. return this;
  48358. };
  48359. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  48360. this._checkUniform(name);
  48361. this._matrices3x3[name] = value;
  48362. return this;
  48363. };
  48364. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  48365. this._checkUniform(name);
  48366. this._matrices2x2[name] = value;
  48367. return this;
  48368. };
  48369. ShaderMaterial.prototype.setArray2 = function (name, value) {
  48370. this._checkUniform(name);
  48371. this._vectors2Arrays[name] = value;
  48372. return this;
  48373. };
  48374. ShaderMaterial.prototype.setArray3 = function (name, value) {
  48375. this._checkUniform(name);
  48376. this._vectors3Arrays[name] = value;
  48377. return this;
  48378. };
  48379. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  48380. if (!mesh) {
  48381. return true;
  48382. }
  48383. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  48384. return false;
  48385. }
  48386. return false;
  48387. };
  48388. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  48389. var scene = this.getScene();
  48390. var engine = scene.getEngine();
  48391. if (!this.checkReadyOnEveryCall) {
  48392. if (this._renderId === scene.getRenderId()) {
  48393. if (this._checkCache(scene, mesh, useInstances)) {
  48394. return true;
  48395. }
  48396. }
  48397. }
  48398. // Instances
  48399. var defines = [];
  48400. var attribs = [];
  48401. var fallbacks = new BABYLON.EffectFallbacks();
  48402. if (useInstances) {
  48403. defines.push("#define INSTANCES");
  48404. }
  48405. for (var index = 0; index < this._options.defines.length; index++) {
  48406. defines.push(this._options.defines[index]);
  48407. }
  48408. for (var index = 0; index < this._options.attributes.length; index++) {
  48409. attribs.push(this._options.attributes[index]);
  48410. }
  48411. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  48412. attribs.push(BABYLON.VertexBuffer.ColorKind);
  48413. defines.push("#define VERTEXCOLOR");
  48414. }
  48415. // Bones
  48416. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  48417. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  48418. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  48419. if (mesh.numBoneInfluencers > 4) {
  48420. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  48421. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  48422. }
  48423. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  48424. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  48425. fallbacks.addCPUSkinningFallback(0, mesh);
  48426. if (this._options.uniforms.indexOf("mBones") === -1) {
  48427. this._options.uniforms.push("mBones");
  48428. }
  48429. }
  48430. else {
  48431. defines.push("#define NUM_BONE_INFLUENCERS 0");
  48432. }
  48433. // Textures
  48434. for (var name in this._textures) {
  48435. if (!this._textures[name].isReady()) {
  48436. return false;
  48437. }
  48438. }
  48439. // Alpha test
  48440. if (engine.getAlphaTesting()) {
  48441. defines.push("#define ALPHATEST");
  48442. }
  48443. var previousEffect = this._effect;
  48444. var join = defines.join("\n");
  48445. this._effect = engine.createEffect(this._shaderPath, {
  48446. attributes: attribs,
  48447. uniformsNames: this._options.uniforms,
  48448. uniformBuffersNames: this._options.uniformBuffers,
  48449. samplers: this._options.samplers,
  48450. defines: join,
  48451. fallbacks: fallbacks,
  48452. onCompiled: this.onCompiled,
  48453. onError: this.onError
  48454. }, engine);
  48455. if (!this._effect.isReady()) {
  48456. return false;
  48457. }
  48458. if (previousEffect !== this._effect) {
  48459. scene.resetCachedMaterial();
  48460. }
  48461. this._renderId = scene.getRenderId();
  48462. return true;
  48463. };
  48464. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  48465. var scene = this.getScene();
  48466. if (!this._effect) {
  48467. return;
  48468. }
  48469. if (this._options.uniforms.indexOf("world") !== -1) {
  48470. this._effect.setMatrix("world", world);
  48471. }
  48472. if (this._options.uniforms.indexOf("worldView") !== -1) {
  48473. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  48474. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  48475. }
  48476. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  48477. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  48478. }
  48479. };
  48480. ShaderMaterial.prototype.bind = function (world, mesh) {
  48481. // Std values
  48482. this.bindOnlyWorldMatrix(world);
  48483. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  48484. if (this._options.uniforms.indexOf("view") !== -1) {
  48485. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  48486. }
  48487. if (this._options.uniforms.indexOf("projection") !== -1) {
  48488. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  48489. }
  48490. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  48491. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  48492. }
  48493. // Bones
  48494. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  48495. var name;
  48496. // Texture
  48497. for (name in this._textures) {
  48498. this._effect.setTexture(name, this._textures[name]);
  48499. }
  48500. // Texture arrays
  48501. for (name in this._textureArrays) {
  48502. this._effect.setTextureArray(name, this._textureArrays[name]);
  48503. }
  48504. // Int
  48505. for (name in this._ints) {
  48506. this._effect.setInt(name, this._ints[name]);
  48507. }
  48508. // Float
  48509. for (name in this._floats) {
  48510. this._effect.setFloat(name, this._floats[name]);
  48511. }
  48512. // Floats
  48513. for (name in this._floatsArrays) {
  48514. this._effect.setArray(name, this._floatsArrays[name]);
  48515. }
  48516. // Color3
  48517. for (name in this._colors3) {
  48518. this._effect.setColor3(name, this._colors3[name]);
  48519. }
  48520. for (name in this._colors3Arrays) {
  48521. this._effect.setArray3(name, this._colors3Arrays[name]);
  48522. }
  48523. // Color4
  48524. for (name in this._colors4) {
  48525. var color = this._colors4[name];
  48526. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  48527. }
  48528. // Vector2
  48529. for (name in this._vectors2) {
  48530. this._effect.setVector2(name, this._vectors2[name]);
  48531. }
  48532. // Vector3
  48533. for (name in this._vectors3) {
  48534. this._effect.setVector3(name, this._vectors3[name]);
  48535. }
  48536. // Vector4
  48537. for (name in this._vectors4) {
  48538. this._effect.setVector4(name, this._vectors4[name]);
  48539. }
  48540. // Matrix
  48541. for (name in this._matrices) {
  48542. this._effect.setMatrix(name, this._matrices[name]);
  48543. }
  48544. // Matrix 3x3
  48545. for (name in this._matrices3x3) {
  48546. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  48547. }
  48548. // Matrix 2x2
  48549. for (name in this._matrices2x2) {
  48550. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  48551. }
  48552. // Vector2Array
  48553. for (name in this._vectors2Arrays) {
  48554. this._effect.setArray2(name, this._vectors2Arrays[name]);
  48555. }
  48556. // Vector3Array
  48557. for (name in this._vectors3Arrays) {
  48558. this._effect.setArray3(name, this._vectors3Arrays[name]);
  48559. }
  48560. }
  48561. this._afterBind(mesh);
  48562. };
  48563. ShaderMaterial.prototype.getActiveTextures = function () {
  48564. var activeTextures = _super.prototype.getActiveTextures.call(this);
  48565. for (var name in this._textures) {
  48566. activeTextures.push(this._textures[name]);
  48567. }
  48568. for (var name in this._textureArrays) {
  48569. var array = this._textureArrays[name];
  48570. for (var index = 0; index < array.length; index++) {
  48571. activeTextures.push(array[index]);
  48572. }
  48573. }
  48574. return activeTextures;
  48575. };
  48576. ShaderMaterial.prototype.hasTexture = function (texture) {
  48577. if (_super.prototype.hasTexture.call(this, texture)) {
  48578. return true;
  48579. }
  48580. for (var name in this._textures) {
  48581. if (this._textures[name] === texture) {
  48582. return true;
  48583. }
  48584. }
  48585. for (var name in this._textureArrays) {
  48586. var array = this._textureArrays[name];
  48587. for (var index = 0; index < array.length; index++) {
  48588. if (array[index] === texture) {
  48589. return true;
  48590. }
  48591. }
  48592. }
  48593. return false;
  48594. };
  48595. ShaderMaterial.prototype.clone = function (name) {
  48596. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  48597. return newShaderMaterial;
  48598. };
  48599. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  48600. if (forceDisposeTextures) {
  48601. var name;
  48602. for (name in this._textures) {
  48603. this._textures[name].dispose();
  48604. }
  48605. for (name in this._textureArrays) {
  48606. var array = this._textureArrays[name];
  48607. for (var index = 0; index < array.length; index++) {
  48608. array[index].dispose();
  48609. }
  48610. }
  48611. }
  48612. this._textures = {};
  48613. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  48614. };
  48615. ShaderMaterial.prototype.serialize = function () {
  48616. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  48617. serializationObject.customType = "BABYLON.ShaderMaterial";
  48618. serializationObject.options = this._options;
  48619. serializationObject.shaderPath = this._shaderPath;
  48620. var name;
  48621. // Texture
  48622. serializationObject.textures = {};
  48623. for (name in this._textures) {
  48624. serializationObject.textures[name] = this._textures[name].serialize();
  48625. }
  48626. // Texture arrays
  48627. serializationObject.textureArrays = {};
  48628. for (name in this._textureArrays) {
  48629. serializationObject.textureArrays[name] = [];
  48630. var array = this._textureArrays[name];
  48631. for (var index = 0; index < array.length; index++) {
  48632. serializationObject.textureArrays[name].push(array[index].serialize());
  48633. }
  48634. }
  48635. // Float
  48636. serializationObject.floats = {};
  48637. for (name in this._floats) {
  48638. serializationObject.floats[name] = this._floats[name];
  48639. }
  48640. // Float s
  48641. serializationObject.FloatArrays = {};
  48642. for (name in this._floatsArrays) {
  48643. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  48644. }
  48645. // Color3
  48646. serializationObject.colors3 = {};
  48647. for (name in this._colors3) {
  48648. serializationObject.colors3[name] = this._colors3[name].asArray();
  48649. }
  48650. // Color3 array
  48651. serializationObject.colors3Arrays = {};
  48652. for (name in this._colors3Arrays) {
  48653. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  48654. }
  48655. // Color4
  48656. serializationObject.colors4 = {};
  48657. for (name in this._colors4) {
  48658. serializationObject.colors4[name] = this._colors4[name].asArray();
  48659. }
  48660. // Vector2
  48661. serializationObject.vectors2 = {};
  48662. for (name in this._vectors2) {
  48663. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  48664. }
  48665. // Vector3
  48666. serializationObject.vectors3 = {};
  48667. for (name in this._vectors3) {
  48668. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  48669. }
  48670. // Vector4
  48671. serializationObject.vectors4 = {};
  48672. for (name in this._vectors4) {
  48673. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  48674. }
  48675. // Matrix
  48676. serializationObject.matrices = {};
  48677. for (name in this._matrices) {
  48678. serializationObject.matrices[name] = this._matrices[name].asArray();
  48679. }
  48680. // Matrix 3x3
  48681. serializationObject.matrices3x3 = {};
  48682. for (name in this._matrices3x3) {
  48683. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  48684. }
  48685. // Matrix 2x2
  48686. serializationObject.matrices2x2 = {};
  48687. for (name in this._matrices2x2) {
  48688. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  48689. }
  48690. // Vector2Array
  48691. serializationObject.vectors2Arrays = {};
  48692. for (name in this._vectors2Arrays) {
  48693. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  48694. }
  48695. // Vector3Array
  48696. serializationObject.vectors3Arrays = {};
  48697. for (name in this._vectors3Arrays) {
  48698. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  48699. }
  48700. return serializationObject;
  48701. };
  48702. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  48703. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  48704. var name;
  48705. // Texture
  48706. for (name in source.textures) {
  48707. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  48708. }
  48709. // Texture arrays
  48710. for (name in source.textureArrays) {
  48711. var array = source.textureArrays[name];
  48712. var textureArray = new Array();
  48713. for (var index = 0; index < array.length; index++) {
  48714. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  48715. }
  48716. material.setTextureArray(name, textureArray);
  48717. }
  48718. // Float
  48719. for (name in source.floats) {
  48720. material.setFloat(name, source.floats[name]);
  48721. }
  48722. // Float s
  48723. for (name in source.floatsArrays) {
  48724. material.setFloats(name, source.floatsArrays[name]);
  48725. }
  48726. // Color3
  48727. for (name in source.colors3) {
  48728. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  48729. }
  48730. // Color3 arrays
  48731. for (name in source.colors3Arrays) {
  48732. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  48733. if (i % 3 === 0) {
  48734. arr.push([num]);
  48735. }
  48736. else {
  48737. arr[arr.length - 1].push(num);
  48738. }
  48739. return arr;
  48740. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  48741. material.setColor3Array(name, colors);
  48742. }
  48743. // Color4
  48744. for (name in source.colors4) {
  48745. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  48746. }
  48747. // Vector2
  48748. for (name in source.vectors2) {
  48749. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  48750. }
  48751. // Vector3
  48752. for (name in source.vectors3) {
  48753. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  48754. }
  48755. // Vector4
  48756. for (name in source.vectors4) {
  48757. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  48758. }
  48759. // Matrix
  48760. for (name in source.matrices) {
  48761. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  48762. }
  48763. // Matrix 3x3
  48764. for (name in source.matrices3x3) {
  48765. material.setMatrix3x3(name, source.matrices3x3[name]);
  48766. }
  48767. // Matrix 2x2
  48768. for (name in source.matrices2x2) {
  48769. material.setMatrix2x2(name, source.matrices2x2[name]);
  48770. }
  48771. // Vector2Array
  48772. for (name in source.vectors2Arrays) {
  48773. material.setArray2(name, source.vectors2Arrays[name]);
  48774. }
  48775. // Vector3Array
  48776. for (name in source.vectors3Arrays) {
  48777. material.setArray3(name, source.vectors3Arrays[name]);
  48778. }
  48779. return material;
  48780. };
  48781. return ShaderMaterial;
  48782. }(BABYLON.Material));
  48783. BABYLON.ShaderMaterial = ShaderMaterial;
  48784. })(BABYLON || (BABYLON = {}));
  48785. //# sourceMappingURL=babylon.shaderMaterial.js.map
  48786. var BABYLON;
  48787. (function (BABYLON) {
  48788. var MeshBuilder = /** @class */ (function () {
  48789. function MeshBuilder() {
  48790. }
  48791. MeshBuilder.updateSideOrientation = function (orientation) {
  48792. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  48793. return BABYLON.Mesh.DOUBLESIDE;
  48794. }
  48795. if (orientation === undefined || orientation === null) {
  48796. return BABYLON.Mesh.FRONTSIDE;
  48797. }
  48798. return orientation;
  48799. };
  48800. /**
  48801. * Creates a box mesh.
  48802. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  48803. * The parameter `size` sets the size (float) of each box side (default 1).
  48804. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  48805. * 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).
  48806. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  48807. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  48808. * 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).
  48809. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  48810. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48811. */
  48812. MeshBuilder.CreateBox = function (name, options, scene) {
  48813. if (scene === void 0) { scene = null; }
  48814. var box = new BABYLON.Mesh(name, scene);
  48815. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  48816. box._originalBuilderSideOrientation = options.sideOrientation;
  48817. var vertexData = BABYLON.VertexData.CreateBox(options);
  48818. vertexData.applyToMesh(box, options.updatable);
  48819. return box;
  48820. };
  48821. /**
  48822. * Creates a sphere mesh.
  48823. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  48824. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  48825. * 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`).
  48826. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  48827. * 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
  48828. * 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).
  48829. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  48830. * 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).
  48831. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  48832. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48833. */
  48834. MeshBuilder.CreateSphere = function (name, options, scene) {
  48835. var sphere = new BABYLON.Mesh(name, scene);
  48836. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  48837. sphere._originalBuilderSideOrientation = options.sideOrientation;
  48838. var vertexData = BABYLON.VertexData.CreateSphere(options);
  48839. vertexData.applyToMesh(sphere, options.updatable);
  48840. return sphere;
  48841. };
  48842. /**
  48843. * Creates a plane polygonal mesh. By default, this is a disc.
  48844. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  48845. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  48846. * 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.
  48847. * 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
  48848. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  48849. * 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).
  48850. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  48851. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48852. */
  48853. MeshBuilder.CreateDisc = function (name, options, scene) {
  48854. if (scene === void 0) { scene = null; }
  48855. var disc = new BABYLON.Mesh(name, scene);
  48856. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  48857. disc._originalBuilderSideOrientation = options.sideOrientation;
  48858. var vertexData = BABYLON.VertexData.CreateDisc(options);
  48859. vertexData.applyToMesh(disc, options.updatable);
  48860. return disc;
  48861. };
  48862. /**
  48863. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  48864. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  48865. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  48866. * 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`).
  48867. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  48868. * 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.
  48869. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  48870. * 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).
  48871. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  48872. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48873. */
  48874. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  48875. var sphere = new BABYLON.Mesh(name, scene);
  48876. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  48877. sphere._originalBuilderSideOrientation = options.sideOrientation;
  48878. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  48879. vertexData.applyToMesh(sphere, options.updatable);
  48880. return sphere;
  48881. };
  48882. ;
  48883. /**
  48884. * Creates a ribbon mesh.
  48885. * 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.
  48886. *
  48887. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  48888. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  48889. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  48890. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  48891. * 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.
  48892. * 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.
  48893. * 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
  48894. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  48895. * 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).
  48896. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  48897. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  48898. * 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.
  48899. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  48900. * 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
  48901. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  48902. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  48903. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  48904. */
  48905. MeshBuilder.CreateRibbon = function (name, options, scene) {
  48906. if (scene === void 0) { scene = null; }
  48907. var pathArray = options.pathArray;
  48908. var closeArray = options.closeArray;
  48909. var closePath = options.closePath;
  48910. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  48911. var instance = options.instance;
  48912. var updatable = options.updatable;
  48913. if (instance) {
  48914. // positionFunction : ribbon case
  48915. // only pathArray and sideOrientation parameters are taken into account for positions update
  48916. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  48917. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  48918. var positionFunction = function (positions) {
  48919. var minlg = pathArray[0].length;
  48920. var i = 0;
  48921. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  48922. for (var si = 1; si <= ns; si++) {
  48923. for (var p = 0; p < pathArray.length; p++) {
  48924. var path = pathArray[p];
  48925. var l = path.length;
  48926. minlg = (minlg < l) ? minlg : l;
  48927. var j = 0;
  48928. while (j < minlg) {
  48929. positions[i] = path[j].x;
  48930. positions[i + 1] = path[j].y;
  48931. positions[i + 2] = path[j].z;
  48932. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  48933. BABYLON.Tmp.Vector3[0].x = path[j].x;
  48934. }
  48935. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  48936. BABYLON.Tmp.Vector3[1].x = path[j].x;
  48937. }
  48938. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  48939. BABYLON.Tmp.Vector3[0].y = path[j].y;
  48940. }
  48941. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  48942. BABYLON.Tmp.Vector3[1].y = path[j].y;
  48943. }
  48944. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  48945. BABYLON.Tmp.Vector3[0].z = path[j].z;
  48946. }
  48947. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  48948. BABYLON.Tmp.Vector3[1].z = path[j].z;
  48949. }
  48950. j++;
  48951. i += 3;
  48952. }
  48953. if (instance._closePath) {
  48954. positions[i] = path[0].x;
  48955. positions[i + 1] = path[0].y;
  48956. positions[i + 2] = path[0].z;
  48957. i += 3;
  48958. }
  48959. }
  48960. }
  48961. };
  48962. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  48963. positionFunction(positions);
  48964. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  48965. instance._boundingInfo.update(instance._worldMatrix);
  48966. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  48967. if (options.colors) {
  48968. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  48969. for (var c = 0; c < options.colors.length; c++) {
  48970. colors[c * 4] = options.colors[c].r;
  48971. colors[c * 4 + 1] = options.colors[c].g;
  48972. colors[c * 4 + 2] = options.colors[c].b;
  48973. colors[c * 4 + 3] = options.colors[c].a;
  48974. }
  48975. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  48976. }
  48977. if (options.uvs) {
  48978. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  48979. for (var i = 0; i < options.uvs.length; i++) {
  48980. uvs[i * 2] = options.uvs[i].x;
  48981. uvs[i * 2 + 1] = options.uvs[i].y;
  48982. }
  48983. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  48984. }
  48985. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  48986. var indices = instance.getIndices();
  48987. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  48988. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  48989. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  48990. if (instance._closePath) {
  48991. var indexFirst = 0;
  48992. var indexLast = 0;
  48993. for (var p = 0; p < pathArray.length; p++) {
  48994. indexFirst = instance._idx[p] * 3;
  48995. if (p + 1 < pathArray.length) {
  48996. indexLast = (instance._idx[p + 1] - 1) * 3;
  48997. }
  48998. else {
  48999. indexLast = normals.length - 3;
  49000. }
  49001. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  49002. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  49003. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  49004. normals[indexLast] = normals[indexFirst];
  49005. normals[indexLast + 1] = normals[indexFirst + 1];
  49006. normals[indexLast + 2] = normals[indexFirst + 2];
  49007. }
  49008. }
  49009. if (!(instance.areNormalsFrozen)) {
  49010. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  49011. }
  49012. }
  49013. return instance;
  49014. }
  49015. else {
  49016. var ribbon = new BABYLON.Mesh(name, scene);
  49017. ribbon._originalBuilderSideOrientation = sideOrientation;
  49018. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  49019. if (closePath) {
  49020. ribbon._idx = vertexData._idx;
  49021. }
  49022. ribbon._closePath = closePath;
  49023. ribbon._closeArray = closeArray;
  49024. vertexData.applyToMesh(ribbon, updatable);
  49025. return ribbon;
  49026. }
  49027. };
  49028. /**
  49029. * Creates a cylinder or a cone mesh.
  49030. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  49031. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  49032. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  49033. * 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.
  49034. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  49035. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  49036. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  49037. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  49038. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  49039. * 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).
  49040. * 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
  49041. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  49042. * 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
  49043. * 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.
  49044. * If `enclose` is false, a ring surface is one element.
  49045. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  49046. * 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
  49047. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  49048. * 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).
  49049. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  49050. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49051. */
  49052. MeshBuilder.CreateCylinder = function (name, options, scene) {
  49053. var cylinder = new BABYLON.Mesh(name, scene);
  49054. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  49055. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  49056. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  49057. vertexData.applyToMesh(cylinder, options.updatable);
  49058. return cylinder;
  49059. };
  49060. /**
  49061. * Creates a torus mesh.
  49062. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  49063. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  49064. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  49065. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  49066. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  49067. * 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).
  49068. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  49069. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49070. */
  49071. MeshBuilder.CreateTorus = function (name, options, scene) {
  49072. var torus = new BABYLON.Mesh(name, scene);
  49073. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  49074. torus._originalBuilderSideOrientation = options.sideOrientation;
  49075. var vertexData = BABYLON.VertexData.CreateTorus(options);
  49076. vertexData.applyToMesh(torus, options.updatable);
  49077. return torus;
  49078. };
  49079. /**
  49080. * Creates a torus knot mesh.
  49081. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  49082. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  49083. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  49084. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  49085. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  49086. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  49087. * 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).
  49088. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  49089. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49090. */
  49091. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  49092. var torusKnot = new BABYLON.Mesh(name, scene);
  49093. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  49094. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  49095. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  49096. vertexData.applyToMesh(torusKnot, options.updatable);
  49097. return torusKnot;
  49098. };
  49099. /**
  49100. * Creates a line system mesh.
  49101. * A line system is a pool of many lines gathered in a single mesh.
  49102. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  49103. * 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.
  49104. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  49105. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  49106. * 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
  49107. * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point.
  49108. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need the alpha blending (faster).
  49109. * 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
  49110. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  49111. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49112. */
  49113. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  49114. var instance = options.instance;
  49115. var lines = options.lines;
  49116. var colors = options.colors;
  49117. if (instance) {
  49118. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  49119. var vertexColor;
  49120. var lineColors;
  49121. if (colors) {
  49122. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  49123. }
  49124. var i = 0;
  49125. var c = 0;
  49126. for (var l = 0; l < lines.length; l++) {
  49127. var points = lines[l];
  49128. for (var p = 0; p < points.length; p++) {
  49129. positions[i] = points[p].x;
  49130. positions[i + 1] = points[p].y;
  49131. positions[i + 2] = points[p].z;
  49132. if (colors && vertexColor) {
  49133. lineColors = colors[l];
  49134. vertexColor[c] = lineColors[p].r;
  49135. vertexColor[c + 1] = lineColors[p].g;
  49136. vertexColor[c + 2] = lineColors[p].b;
  49137. vertexColor[c + 3] = lineColors[p].a;
  49138. c += 4;
  49139. }
  49140. i += 3;
  49141. }
  49142. }
  49143. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  49144. if (colors && vertexColor) {
  49145. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  49146. }
  49147. return instance;
  49148. }
  49149. // line system creation
  49150. var useVertexColor = (colors) ? true : false;
  49151. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  49152. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  49153. vertexData.applyToMesh(lineSystem, options.updatable);
  49154. return lineSystem;
  49155. };
  49156. /**
  49157. * Creates a line mesh.
  49158. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  49159. * 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.
  49160. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  49161. * The parameter `points` is an array successive Vector3.
  49162. * 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
  49163. * The optional parameter `colors` is an array of successive Color4, one per line point.
  49164. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need alpha blending (faster).
  49165. * When updating an instance, remember that only point positions can change, not the number of points.
  49166. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49167. */
  49168. MeshBuilder.CreateLines = function (name, options, scene) {
  49169. if (scene === void 0) { scene = null; }
  49170. var colors = (options.colors) ? [options.colors] : null;
  49171. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  49172. return lines;
  49173. };
  49174. /**
  49175. * Creates a dashed line mesh.
  49176. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  49177. * 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.
  49178. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  49179. * The parameter `points` is an array successive Vector3.
  49180. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  49181. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  49182. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  49183. * 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
  49184. * When updating an instance, remember that only point positions can change, not the number of points.
  49185. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49186. */
  49187. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  49188. if (scene === void 0) { scene = null; }
  49189. var points = options.points;
  49190. var instance = options.instance;
  49191. var gapSize = options.gapSize || 1;
  49192. var dashSize = options.dashSize || 3;
  49193. if (instance) {
  49194. var positionFunction = function (positions) {
  49195. var curvect = BABYLON.Vector3.Zero();
  49196. var nbSeg = positions.length / 6;
  49197. var lg = 0;
  49198. var nb = 0;
  49199. var shft = 0;
  49200. var dashshft = 0;
  49201. var curshft = 0;
  49202. var p = 0;
  49203. var i = 0;
  49204. var j = 0;
  49205. for (i = 0; i < points.length - 1; i++) {
  49206. points[i + 1].subtractToRef(points[i], curvect);
  49207. lg += curvect.length();
  49208. }
  49209. shft = lg / nbSeg;
  49210. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  49211. for (i = 0; i < points.length - 1; i++) {
  49212. points[i + 1].subtractToRef(points[i], curvect);
  49213. nb = Math.floor(curvect.length() / shft);
  49214. curvect.normalize();
  49215. j = 0;
  49216. while (j < nb && p < positions.length) {
  49217. curshft = shft * j;
  49218. positions[p] = points[i].x + curshft * curvect.x;
  49219. positions[p + 1] = points[i].y + curshft * curvect.y;
  49220. positions[p + 2] = points[i].z + curshft * curvect.z;
  49221. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  49222. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  49223. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  49224. p += 6;
  49225. j++;
  49226. }
  49227. }
  49228. while (p < positions.length) {
  49229. positions[p] = points[i].x;
  49230. positions[p + 1] = points[i].y;
  49231. positions[p + 2] = points[i].z;
  49232. p += 3;
  49233. }
  49234. };
  49235. instance.updateMeshPositions(positionFunction, false);
  49236. return instance;
  49237. }
  49238. // dashed lines creation
  49239. var dashedLines = new BABYLON.LinesMesh(name, scene);
  49240. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  49241. vertexData.applyToMesh(dashedLines, options.updatable);
  49242. dashedLines.dashSize = dashSize;
  49243. dashedLines.gapSize = gapSize;
  49244. return dashedLines;
  49245. };
  49246. /**
  49247. * Creates an extruded shape mesh.
  49248. * 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.
  49249. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  49250. *
  49251. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  49252. * 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
  49253. * extruded along the Z axis.
  49254. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  49255. * 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.
  49256. * The parameter `scale` (float, default 1) is the value to scale the shape.
  49257. * 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
  49258. * 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
  49259. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  49260. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  49261. * 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).
  49262. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  49263. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  49264. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49265. */
  49266. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  49267. if (scene === void 0) { scene = null; }
  49268. var path = options.path;
  49269. var shape = options.shape;
  49270. var scale = options.scale || 1;
  49271. var rotation = options.rotation || 0;
  49272. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  49273. var updatable = options.updatable;
  49274. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  49275. var instance = options.instance || null;
  49276. var invertUV = options.invertUV || false;
  49277. 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);
  49278. };
  49279. /**
  49280. * Creates an custom extruded shape mesh.
  49281. * 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.
  49282. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  49283. *
  49284. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  49285. * 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
  49286. * extruded along the Z axis.
  49287. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  49288. * 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
  49289. * and the distance of this point from the begining of the path :
  49290. * ```javascript
  49291. * var rotationFunction = function(i, distance) {
  49292. * // do things
  49293. * return rotationValue; }
  49294. * ```
  49295. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  49296. * 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
  49297. * and the distance of this point from the begining of the path :
  49298. * ```javascript
  49299. * var scaleFunction = function(i, distance) {
  49300. * // do things
  49301. * return scaleValue;}
  49302. * ```
  49303. * It must returns a float value that will be the scale value applied to the shape on each path point.
  49304. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  49305. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  49306. * 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
  49307. * 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
  49308. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  49309. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  49310. * 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).
  49311. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  49312. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  49313. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49314. */
  49315. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  49316. var path = options.path;
  49317. var shape = options.shape;
  49318. var scaleFunction = options.scaleFunction || (function () { return 1; });
  49319. var rotationFunction = options.rotationFunction || (function () { return 0; });
  49320. var ribbonCloseArray = options.ribbonCloseArray || false;
  49321. var ribbonClosePath = options.ribbonClosePath || false;
  49322. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  49323. var updatable = options.updatable;
  49324. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  49325. var instance = options.instance;
  49326. var invertUV = options.invertUV || false;
  49327. 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);
  49328. };
  49329. /**
  49330. * Creates lathe mesh.
  49331. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  49332. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  49333. *
  49334. * 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
  49335. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  49336. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  49337. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  49338. * 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.
  49339. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  49340. * 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
  49341. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  49342. * 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).
  49343. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  49344. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  49345. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49346. */
  49347. MeshBuilder.CreateLathe = function (name, options, scene) {
  49348. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  49349. var closed = (options.closed === undefined) ? true : options.closed;
  49350. var shape = options.shape;
  49351. var radius = options.radius || 1;
  49352. var tessellation = options.tessellation || 64;
  49353. var updatable = options.updatable;
  49354. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  49355. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  49356. var pi2 = Math.PI * 2;
  49357. var paths = new Array();
  49358. var invertUV = options.invertUV || false;
  49359. var i = 0;
  49360. var p = 0;
  49361. var step = pi2 / tessellation * arc;
  49362. var rotated;
  49363. var path = new Array();
  49364. ;
  49365. for (i = 0; i <= tessellation; i++) {
  49366. var path = [];
  49367. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  49368. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  49369. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  49370. }
  49371. for (p = 0; p < shape.length; p++) {
  49372. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  49373. path.push(rotated);
  49374. }
  49375. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  49376. 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));
  49377. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  49378. }
  49379. paths.push(path);
  49380. }
  49381. // lathe ribbon
  49382. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  49383. return lathe;
  49384. };
  49385. /**
  49386. * Creates a plane mesh.
  49387. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  49388. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  49389. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  49390. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  49391. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  49392. * 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).
  49393. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  49394. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49395. */
  49396. MeshBuilder.CreatePlane = function (name, options, scene) {
  49397. var plane = new BABYLON.Mesh(name, scene);
  49398. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  49399. plane._originalBuilderSideOrientation = options.sideOrientation;
  49400. var vertexData = BABYLON.VertexData.CreatePlane(options);
  49401. vertexData.applyToMesh(plane, options.updatable);
  49402. if (options.sourcePlane) {
  49403. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  49404. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  49405. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  49406. plane.rotate(vectorProduct, product);
  49407. }
  49408. return plane;
  49409. };
  49410. /**
  49411. * Creates a ground mesh.
  49412. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  49413. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  49414. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  49415. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49416. */
  49417. MeshBuilder.CreateGround = function (name, options, scene) {
  49418. var ground = new BABYLON.GroundMesh(name, scene);
  49419. ground._setReady(false);
  49420. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  49421. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  49422. ground._width = options.width || 1;
  49423. ground._height = options.height || 1;
  49424. ground._maxX = ground._width / 2;
  49425. ground._maxZ = ground._height / 2;
  49426. ground._minX = -ground._maxX;
  49427. ground._minZ = -ground._maxZ;
  49428. var vertexData = BABYLON.VertexData.CreateGround(options);
  49429. vertexData.applyToMesh(ground, options.updatable);
  49430. ground._setReady(true);
  49431. return ground;
  49432. };
  49433. /**
  49434. * Creates a tiled ground mesh.
  49435. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  49436. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  49437. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  49438. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  49439. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  49440. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  49441. * numbers of subdivisions on the ground width and height of each tile.
  49442. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49443. */
  49444. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  49445. var tiledGround = new BABYLON.Mesh(name, scene);
  49446. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  49447. vertexData.applyToMesh(tiledGround, options.updatable);
  49448. return tiledGround;
  49449. };
  49450. /**
  49451. * Creates a ground mesh from a height map.
  49452. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  49453. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  49454. * The parameter `url` sets the URL of the height map image resource.
  49455. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  49456. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  49457. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  49458. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  49459. * 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.
  49460. * 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).
  49461. * This function is passed the newly built mesh :
  49462. * ```javascript
  49463. * function(mesh) { // do things
  49464. * return; }
  49465. * ```
  49466. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49467. */
  49468. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  49469. var width = options.width || 10.0;
  49470. var height = options.height || 10.0;
  49471. var subdivisions = options.subdivisions || 1 | 0;
  49472. var minHeight = options.minHeight || 0.0;
  49473. var maxHeight = options.maxHeight || 1.0;
  49474. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  49475. var updatable = options.updatable;
  49476. var onReady = options.onReady;
  49477. var ground = new BABYLON.GroundMesh(name, scene);
  49478. ground._subdivisionsX = subdivisions;
  49479. ground._subdivisionsY = subdivisions;
  49480. ground._width = width;
  49481. ground._height = height;
  49482. ground._maxX = ground._width / 2.0;
  49483. ground._maxZ = ground._height / 2.0;
  49484. ground._minX = -ground._maxX;
  49485. ground._minZ = -ground._maxZ;
  49486. ground._setReady(false);
  49487. var onload = function (img) {
  49488. // Getting height map data
  49489. var canvas = document.createElement("canvas");
  49490. var context = canvas.getContext("2d");
  49491. if (!context) {
  49492. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  49493. }
  49494. var bufferWidth = img.width;
  49495. var bufferHeight = img.height;
  49496. canvas.width = bufferWidth;
  49497. canvas.height = bufferHeight;
  49498. context.drawImage(img, 0, 0);
  49499. // Create VertexData from map data
  49500. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  49501. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  49502. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  49503. width: width, height: height,
  49504. subdivisions: subdivisions,
  49505. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  49506. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  49507. });
  49508. vertexData.applyToMesh(ground, updatable);
  49509. ground._setReady(true);
  49510. //execute ready callback, if set
  49511. if (onReady) {
  49512. onReady(ground);
  49513. }
  49514. };
  49515. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  49516. return ground;
  49517. };
  49518. /**
  49519. * Creates a polygon mesh.
  49520. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  49521. * 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.
  49522. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  49523. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49524. * 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).
  49525. * Remember you can only change the shape positions, not their number when updating a polygon.
  49526. */
  49527. MeshBuilder.CreatePolygon = function (name, options, scene) {
  49528. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  49529. var shape = options.shape;
  49530. var holes = options.holes || [];
  49531. var depth = options.depth || 0;
  49532. var contours = [];
  49533. var hole = [];
  49534. for (var i = 0; i < shape.length; i++) {
  49535. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  49536. }
  49537. var epsilon = 0.00000001;
  49538. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  49539. contours.pop();
  49540. }
  49541. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  49542. for (var hNb = 0; hNb < holes.length; hNb++) {
  49543. hole = [];
  49544. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  49545. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  49546. }
  49547. polygonTriangulation.addHole(hole);
  49548. }
  49549. var polygon = polygonTriangulation.build(options.updatable, depth);
  49550. polygon._originalBuilderSideOrientation = options.sideOrientation;
  49551. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  49552. vertexData.applyToMesh(polygon, options.updatable);
  49553. return polygon;
  49554. };
  49555. ;
  49556. /**
  49557. * Creates an extruded polygon mesh, with depth in the Y direction.
  49558. * 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).
  49559. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  49560. */
  49561. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  49562. return MeshBuilder.CreatePolygon(name, options, scene);
  49563. };
  49564. ;
  49565. /**
  49566. * Creates a tube mesh.
  49567. * 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.
  49568. *
  49569. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  49570. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  49571. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  49572. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  49573. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  49574. * 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.
  49575. * It must return a radius value (positive float) :
  49576. * ```javascript
  49577. * var radiusFunction = function(i, distance) {
  49578. * // do things
  49579. * return radius; }
  49580. * ```
  49581. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  49582. * 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
  49583. * 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
  49584. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  49585. * 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).
  49586. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  49587. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  49588. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49589. */
  49590. MeshBuilder.CreateTube = function (name, options, scene) {
  49591. var path = options.path;
  49592. var instance = options.instance;
  49593. var radius = 1.0;
  49594. if (instance) {
  49595. radius = instance.radius;
  49596. }
  49597. if (options.radius !== undefined) {
  49598. radius = options.radius;
  49599. }
  49600. ;
  49601. var tessellation = options.tessellation || 64 | 0;
  49602. var radiusFunction = options.radiusFunction || null;
  49603. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  49604. var invertUV = options.invertUV || false;
  49605. var updatable = options.updatable;
  49606. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  49607. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  49608. // tube geometry
  49609. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  49610. var tangents = path3D.getTangents();
  49611. var normals = path3D.getNormals();
  49612. var distances = path3D.getDistances();
  49613. var pi2 = Math.PI * 2;
  49614. var step = pi2 / tessellation * arc;
  49615. var returnRadius = function () { return radius; };
  49616. var radiusFunctionFinal = radiusFunction || returnRadius;
  49617. var circlePath;
  49618. var rad;
  49619. var normal;
  49620. var rotated;
  49621. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  49622. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  49623. for (var i = 0; i < path.length; i++) {
  49624. rad = radiusFunctionFinal(i, distances[i]); // current radius
  49625. circlePath = Array(); // current circle array
  49626. normal = normals[i]; // current normal
  49627. for (var t = 0; t < tessellation; t++) {
  49628. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  49629. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  49630. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  49631. rotated.scaleInPlace(rad).addInPlace(path[i]);
  49632. circlePath[t] = rotated;
  49633. }
  49634. circlePaths[index] = circlePath;
  49635. index++;
  49636. }
  49637. // cap
  49638. var capPath = function (nbPoints, pathIndex) {
  49639. var pointCap = Array();
  49640. for (var i = 0; i < nbPoints; i++) {
  49641. pointCap.push(path[pathIndex]);
  49642. }
  49643. return pointCap;
  49644. };
  49645. switch (cap) {
  49646. case BABYLON.Mesh.NO_CAP:
  49647. break;
  49648. case BABYLON.Mesh.CAP_START:
  49649. circlePaths[0] = capPath(tessellation, 0);
  49650. circlePaths[1] = circlePaths[2].slice(0);
  49651. break;
  49652. case BABYLON.Mesh.CAP_END:
  49653. circlePaths[index] = circlePaths[index - 1].slice(0);
  49654. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  49655. break;
  49656. case BABYLON.Mesh.CAP_ALL:
  49657. circlePaths[0] = capPath(tessellation, 0);
  49658. circlePaths[1] = circlePaths[2].slice(0);
  49659. circlePaths[index] = circlePaths[index - 1].slice(0);
  49660. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  49661. break;
  49662. default:
  49663. break;
  49664. }
  49665. return circlePaths;
  49666. };
  49667. var path3D;
  49668. var pathArray;
  49669. if (instance) {
  49670. var arc = options.arc || instance.arc;
  49671. path3D = (instance.path3D).update(path);
  49672. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  49673. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  49674. instance.path3D = path3D;
  49675. instance.pathArray = pathArray;
  49676. instance.arc = arc;
  49677. instance.radius = radius;
  49678. return instance;
  49679. }
  49680. // tube creation
  49681. path3D = new BABYLON.Path3D(path);
  49682. var newPathArray = new Array();
  49683. cap = (cap < 0 || cap > 3) ? 0 : cap;
  49684. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  49685. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  49686. tube.pathArray = pathArray;
  49687. tube.path3D = path3D;
  49688. tube.tessellation = tessellation;
  49689. tube.cap = cap;
  49690. tube.arc = options.arc;
  49691. tube.radius = radius;
  49692. return tube;
  49693. };
  49694. /**
  49695. * Creates a polyhedron mesh.
  49696. *
  49697. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  49698. * 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
  49699. * to choose the wanted type.
  49700. * The parameter `size` (positive float, default 1) sets the polygon size.
  49701. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  49702. * 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`.
  49703. * 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
  49704. * 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)`).
  49705. * 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
  49706. * 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.
  49707. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  49708. * 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).
  49709. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  49710. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  49711. */
  49712. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  49713. var polyhedron = new BABYLON.Mesh(name, scene);
  49714. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  49715. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  49716. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  49717. vertexData.applyToMesh(polyhedron, options.updatable);
  49718. return polyhedron;
  49719. };
  49720. /**
  49721. * Creates a decal mesh.
  49722. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  49723. * 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.
  49724. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  49725. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  49726. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  49727. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  49728. */
  49729. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  49730. var indices = sourceMesh.getIndices();
  49731. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  49732. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  49733. var position = options.position || BABYLON.Vector3.Zero();
  49734. var normal = options.normal || BABYLON.Vector3.Up();
  49735. var size = options.size || BABYLON.Vector3.One();
  49736. var angle = options.angle || 0;
  49737. // Getting correct rotation
  49738. if (!normal) {
  49739. var target = new BABYLON.Vector3(0, 0, 1);
  49740. var camera = sourceMesh.getScene().activeCamera;
  49741. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  49742. normal = camera.globalPosition.subtract(cameraWorldTarget);
  49743. }
  49744. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  49745. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  49746. var pitch = Math.atan2(normal.y, len);
  49747. // Matrix
  49748. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  49749. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  49750. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  49751. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  49752. var vertexData = new BABYLON.VertexData();
  49753. vertexData.indices = [];
  49754. vertexData.positions = [];
  49755. vertexData.normals = [];
  49756. vertexData.uvs = [];
  49757. var currentVertexDataIndex = 0;
  49758. var extractDecalVector3 = function (indexId) {
  49759. var result = new BABYLON.PositionNormalVertex();
  49760. if (!indices || !positions || !normals) {
  49761. return result;
  49762. }
  49763. var vertexId = indices[indexId];
  49764. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  49765. // Send vector to decal local world
  49766. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  49767. // Get normal
  49768. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  49769. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  49770. return result;
  49771. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  49772. var clip = function (vertices, axis) {
  49773. if (vertices.length === 0) {
  49774. return vertices;
  49775. }
  49776. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  49777. var clipVertices = function (v0, v1) {
  49778. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  49779. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  49780. };
  49781. var result = new Array();
  49782. for (var index = 0; index < vertices.length; index += 3) {
  49783. var v1Out;
  49784. var v2Out;
  49785. var v3Out;
  49786. var total = 0;
  49787. var nV1 = null;
  49788. var nV2 = null;
  49789. var nV3 = null;
  49790. var nV4 = null;
  49791. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  49792. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  49793. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  49794. v1Out = d1 > 0;
  49795. v2Out = d2 > 0;
  49796. v3Out = d3 > 0;
  49797. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  49798. switch (total) {
  49799. case 0:
  49800. result.push(vertices[index]);
  49801. result.push(vertices[index + 1]);
  49802. result.push(vertices[index + 2]);
  49803. break;
  49804. case 1:
  49805. if (v1Out) {
  49806. nV1 = vertices[index + 1];
  49807. nV2 = vertices[index + 2];
  49808. nV3 = clipVertices(vertices[index], nV1);
  49809. nV4 = clipVertices(vertices[index], nV2);
  49810. }
  49811. if (v2Out) {
  49812. nV1 = vertices[index];
  49813. nV2 = vertices[index + 2];
  49814. nV3 = clipVertices(vertices[index + 1], nV1);
  49815. nV4 = clipVertices(vertices[index + 1], nV2);
  49816. result.push(nV3);
  49817. result.push(nV2.clone());
  49818. result.push(nV1.clone());
  49819. result.push(nV2.clone());
  49820. result.push(nV3.clone());
  49821. result.push(nV4);
  49822. break;
  49823. }
  49824. if (v3Out) {
  49825. nV1 = vertices[index];
  49826. nV2 = vertices[index + 1];
  49827. nV3 = clipVertices(vertices[index + 2], nV1);
  49828. nV4 = clipVertices(vertices[index + 2], nV2);
  49829. }
  49830. if (nV1 && nV2 && nV3 && nV4) {
  49831. result.push(nV1.clone());
  49832. result.push(nV2.clone());
  49833. result.push(nV3);
  49834. result.push(nV4);
  49835. result.push(nV3.clone());
  49836. result.push(nV2.clone());
  49837. }
  49838. break;
  49839. case 2:
  49840. if (!v1Out) {
  49841. nV1 = vertices[index].clone();
  49842. nV2 = clipVertices(nV1, vertices[index + 1]);
  49843. nV3 = clipVertices(nV1, vertices[index + 2]);
  49844. result.push(nV1);
  49845. result.push(nV2);
  49846. result.push(nV3);
  49847. }
  49848. if (!v2Out) {
  49849. nV1 = vertices[index + 1].clone();
  49850. nV2 = clipVertices(nV1, vertices[index + 2]);
  49851. nV3 = clipVertices(nV1, vertices[index]);
  49852. result.push(nV1);
  49853. result.push(nV2);
  49854. result.push(nV3);
  49855. }
  49856. if (!v3Out) {
  49857. nV1 = vertices[index + 2].clone();
  49858. nV2 = clipVertices(nV1, vertices[index]);
  49859. nV3 = clipVertices(nV1, vertices[index + 1]);
  49860. result.push(nV1);
  49861. result.push(nV2);
  49862. result.push(nV3);
  49863. }
  49864. break;
  49865. case 3:
  49866. break;
  49867. }
  49868. }
  49869. return result;
  49870. };
  49871. for (var index = 0; index < indices.length; index += 3) {
  49872. var faceVertices = new Array();
  49873. faceVertices.push(extractDecalVector3(index));
  49874. faceVertices.push(extractDecalVector3(index + 1));
  49875. faceVertices.push(extractDecalVector3(index + 2));
  49876. // Clip
  49877. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  49878. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  49879. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  49880. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  49881. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  49882. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  49883. if (faceVertices.length === 0) {
  49884. continue;
  49885. }
  49886. // Add UVs and get back to world
  49887. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  49888. var vertex = faceVertices[vIndex];
  49889. //TODO check for Int32Array | Uint32Array | Uint16Array
  49890. vertexData.indices.push(currentVertexDataIndex);
  49891. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  49892. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  49893. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  49894. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  49895. currentVertexDataIndex++;
  49896. }
  49897. }
  49898. // Return mesh
  49899. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  49900. vertexData.applyToMesh(decal);
  49901. decal.position = position.clone();
  49902. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  49903. return decal;
  49904. };
  49905. // Privates
  49906. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  49907. // extrusion geometry
  49908. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  49909. var tangents = path3D.getTangents();
  49910. var normals = path3D.getNormals();
  49911. var binormals = path3D.getBinormals();
  49912. var distances = path3D.getDistances();
  49913. var angle = 0;
  49914. var returnScale = function () { return scale !== null ? scale : 1; };
  49915. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  49916. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  49917. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  49918. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  49919. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  49920. for (var i = 0; i < curve.length; i++) {
  49921. var shapePath = new Array();
  49922. var angleStep = rotate(i, distances[i]);
  49923. var scaleRatio = scl(i, distances[i]);
  49924. for (var p = 0; p < shape.length; p++) {
  49925. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  49926. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  49927. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  49928. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  49929. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  49930. shapePath[p] = rotated;
  49931. }
  49932. shapePaths[index] = shapePath;
  49933. angle += angleStep;
  49934. index++;
  49935. }
  49936. // cap
  49937. var capPath = function (shapePath) {
  49938. var pointCap = Array();
  49939. var barycenter = BABYLON.Vector3.Zero();
  49940. var i;
  49941. for (i = 0; i < shapePath.length; i++) {
  49942. barycenter.addInPlace(shapePath[i]);
  49943. }
  49944. barycenter.scaleInPlace(1.0 / shapePath.length);
  49945. for (i = 0; i < shapePath.length; i++) {
  49946. pointCap.push(barycenter);
  49947. }
  49948. return pointCap;
  49949. };
  49950. switch (cap) {
  49951. case BABYLON.Mesh.NO_CAP:
  49952. break;
  49953. case BABYLON.Mesh.CAP_START:
  49954. shapePaths[0] = capPath(shapePaths[2]);
  49955. shapePaths[1] = shapePaths[2];
  49956. break;
  49957. case BABYLON.Mesh.CAP_END:
  49958. shapePaths[index] = shapePaths[index - 1];
  49959. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  49960. break;
  49961. case BABYLON.Mesh.CAP_ALL:
  49962. shapePaths[0] = capPath(shapePaths[2]);
  49963. shapePaths[1] = shapePaths[2];
  49964. shapePaths[index] = shapePaths[index - 1];
  49965. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  49966. break;
  49967. default:
  49968. break;
  49969. }
  49970. return shapePaths;
  49971. };
  49972. var path3D;
  49973. var pathArray;
  49974. if (instance) {
  49975. path3D = (instance.path3D).update(curve);
  49976. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  49977. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  49978. return instance;
  49979. }
  49980. // extruded shape creation
  49981. path3D = new BABYLON.Path3D(curve);
  49982. var newShapePaths = new Array();
  49983. cap = (cap < 0 || cap > 3) ? 0 : cap;
  49984. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  49985. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  49986. extrudedGeneric.pathArray = pathArray;
  49987. extrudedGeneric.path3D = path3D;
  49988. extrudedGeneric.cap = cap;
  49989. return extrudedGeneric;
  49990. };
  49991. return MeshBuilder;
  49992. }());
  49993. BABYLON.MeshBuilder = MeshBuilder;
  49994. })(BABYLON || (BABYLON = {}));
  49995. //# sourceMappingURL=babylon.meshBuilder.js.map
  49996. var BABYLON;
  49997. (function (BABYLON) {
  49998. var AudioEngine = /** @class */ (function () {
  49999. function AudioEngine() {
  50000. this._audioContext = null;
  50001. this._audioContextInitialized = false;
  50002. this.canUseWebAudio = false;
  50003. this.WarnedWebAudioUnsupported = false;
  50004. this.unlocked = false;
  50005. this.isMP3supported = false;
  50006. this.isOGGsupported = false;
  50007. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  50008. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  50009. this.canUseWebAudio = true;
  50010. }
  50011. var audioElem = document.createElement('audio');
  50012. try {
  50013. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  50014. this.isMP3supported = true;
  50015. }
  50016. }
  50017. catch (e) {
  50018. // protect error during capability check.
  50019. }
  50020. try {
  50021. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  50022. this.isOGGsupported = true;
  50023. }
  50024. }
  50025. catch (e) {
  50026. // protect error during capability check.
  50027. }
  50028. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  50029. this._unlockiOSaudio();
  50030. }
  50031. else {
  50032. this.unlocked = true;
  50033. }
  50034. }
  50035. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  50036. get: function () {
  50037. if (!this._audioContextInitialized) {
  50038. this._initializeAudioContext();
  50039. }
  50040. return this._audioContext;
  50041. },
  50042. enumerable: true,
  50043. configurable: true
  50044. });
  50045. AudioEngine.prototype._unlockiOSaudio = function () {
  50046. var _this = this;
  50047. var unlockaudio = function () {
  50048. if (!_this.audioContext) {
  50049. return;
  50050. }
  50051. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  50052. var source = _this.audioContext.createBufferSource();
  50053. source.buffer = buffer;
  50054. source.connect(_this.audioContext.destination);
  50055. source.start(0);
  50056. setTimeout(function () {
  50057. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  50058. _this.unlocked = true;
  50059. window.removeEventListener('touchend', unlockaudio, false);
  50060. if (_this.onAudioUnlocked) {
  50061. _this.onAudioUnlocked();
  50062. }
  50063. }
  50064. }, 0);
  50065. };
  50066. window.addEventListener('touchend', unlockaudio, false);
  50067. };
  50068. AudioEngine.prototype._initializeAudioContext = function () {
  50069. try {
  50070. if (this.canUseWebAudio) {
  50071. this._audioContext = new AudioContext();
  50072. // create a global volume gain node
  50073. this.masterGain = this._audioContext.createGain();
  50074. this.masterGain.gain.value = 1;
  50075. this.masterGain.connect(this._audioContext.destination);
  50076. this._audioContextInitialized = true;
  50077. }
  50078. }
  50079. catch (e) {
  50080. this.canUseWebAudio = false;
  50081. BABYLON.Tools.Error("Web Audio: " + e.message);
  50082. }
  50083. };
  50084. AudioEngine.prototype.dispose = function () {
  50085. if (this.canUseWebAudio && this._audioContextInitialized) {
  50086. if (this._connectedAnalyser && this._audioContext) {
  50087. this._connectedAnalyser.stopDebugCanvas();
  50088. this._connectedAnalyser.dispose();
  50089. this.masterGain.disconnect();
  50090. this.masterGain.connect(this._audioContext.destination);
  50091. this._connectedAnalyser = null;
  50092. }
  50093. this.masterGain.gain.value = 1;
  50094. }
  50095. this.WarnedWebAudioUnsupported = false;
  50096. };
  50097. AudioEngine.prototype.getGlobalVolume = function () {
  50098. if (this.canUseWebAudio && this._audioContextInitialized) {
  50099. return this.masterGain.gain.value;
  50100. }
  50101. else {
  50102. return -1;
  50103. }
  50104. };
  50105. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  50106. if (this.canUseWebAudio && this._audioContextInitialized) {
  50107. this.masterGain.gain.value = newVolume;
  50108. }
  50109. };
  50110. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  50111. if (this._connectedAnalyser) {
  50112. this._connectedAnalyser.stopDebugCanvas();
  50113. }
  50114. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  50115. this._connectedAnalyser = analyser;
  50116. this.masterGain.disconnect();
  50117. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  50118. }
  50119. };
  50120. return AudioEngine;
  50121. }());
  50122. BABYLON.AudioEngine = AudioEngine;
  50123. })(BABYLON || (BABYLON = {}));
  50124. //# sourceMappingURL=babylon.audioEngine.js.map
  50125. var BABYLON;
  50126. (function (BABYLON) {
  50127. var Sound = /** @class */ (function () {
  50128. /**
  50129. * Create a sound and attach it to a scene
  50130. * @param name Name of your sound
  50131. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  50132. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  50133. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  50134. */
  50135. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  50136. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  50137. var _this = this;
  50138. this.autoplay = false;
  50139. this.loop = false;
  50140. this.useCustomAttenuation = false;
  50141. this.spatialSound = false;
  50142. this.refDistance = 1;
  50143. this.rolloffFactor = 1;
  50144. this.maxDistance = 100;
  50145. this.distanceModel = "linear";
  50146. this._panningModel = "equalpower";
  50147. this._playbackRate = 1;
  50148. this._streaming = false;
  50149. this._startTime = 0;
  50150. this._startOffset = 0;
  50151. this._position = BABYLON.Vector3.Zero();
  50152. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  50153. this._volume = 1;
  50154. this._isReadyToPlay = false;
  50155. this.isPlaying = false;
  50156. this.isPaused = false;
  50157. this._isDirectional = false;
  50158. // Used if you'd like to create a directional sound.
  50159. // If not set, the sound will be omnidirectional
  50160. this._coneInnerAngle = 360;
  50161. this._coneOuterAngle = 360;
  50162. this._coneOuterGain = 0;
  50163. this._isOutputConnected = false;
  50164. this._urlType = "Unknown";
  50165. this.name = name;
  50166. this._scene = scene;
  50167. this._readyToPlayCallback = readyToPlayCallback;
  50168. // Default custom attenuation function is a linear attenuation
  50169. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  50170. if (currentDistance < maxDistance) {
  50171. return currentVolume * (1 - currentDistance / maxDistance);
  50172. }
  50173. else {
  50174. return 0;
  50175. }
  50176. };
  50177. if (options) {
  50178. this.autoplay = options.autoplay || false;
  50179. this.loop = options.loop || false;
  50180. // if volume === 0, we need another way to check this option
  50181. if (options.volume !== undefined) {
  50182. this._volume = options.volume;
  50183. }
  50184. this.spatialSound = options.spatialSound || false;
  50185. this.maxDistance = options.maxDistance || 100;
  50186. this.useCustomAttenuation = options.useCustomAttenuation || false;
  50187. this.rolloffFactor = options.rolloffFactor || 1;
  50188. this.refDistance = options.refDistance || 1;
  50189. this.distanceModel = options.distanceModel || "linear";
  50190. this._playbackRate = options.playbackRate || 1;
  50191. this._streaming = options.streaming || false;
  50192. }
  50193. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  50194. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  50195. this._soundGain.gain.value = this._volume;
  50196. this._inputAudioNode = this._soundGain;
  50197. this._ouputAudioNode = this._soundGain;
  50198. if (this.spatialSound) {
  50199. this._createSpatialParameters();
  50200. }
  50201. this._scene.mainSoundTrack.AddSound(this);
  50202. var validParameter = true;
  50203. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  50204. if (urlOrArrayBuffer) {
  50205. if (typeof (urlOrArrayBuffer) === "string")
  50206. this._urlType = "String";
  50207. if (Array.isArray(urlOrArrayBuffer))
  50208. this._urlType = "Array";
  50209. if (urlOrArrayBuffer instanceof ArrayBuffer)
  50210. this._urlType = "ArrayBuffer";
  50211. var urls = [];
  50212. var codecSupportedFound = false;
  50213. switch (this._urlType) {
  50214. case "ArrayBuffer":
  50215. if (urlOrArrayBuffer.byteLength > 0) {
  50216. codecSupportedFound = true;
  50217. this._soundLoaded(urlOrArrayBuffer);
  50218. }
  50219. break;
  50220. case "String":
  50221. urls.push(urlOrArrayBuffer);
  50222. case "Array":
  50223. if (urls.length === 0)
  50224. urls = urlOrArrayBuffer;
  50225. // If we found a supported format, we load it immediately and stop the loop
  50226. for (var i = 0; i < urls.length; i++) {
  50227. var url = urls[i];
  50228. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  50229. codecSupportedFound = true;
  50230. }
  50231. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  50232. codecSupportedFound = true;
  50233. }
  50234. if (url.indexOf(".wav", url.length - 4) !== -1) {
  50235. codecSupportedFound = true;
  50236. }
  50237. if (url.indexOf("blob:") !== -1) {
  50238. codecSupportedFound = true;
  50239. }
  50240. if (codecSupportedFound) {
  50241. // Loading sound using XHR2
  50242. if (!this._streaming) {
  50243. this._scene._loadFile(url, function (data) { _this._soundLoaded(data); }, undefined, true, true);
  50244. }
  50245. else {
  50246. this._htmlAudioElement = new Audio(url);
  50247. this._htmlAudioElement.controls = false;
  50248. this._htmlAudioElement.loop = this.loop;
  50249. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  50250. this._htmlAudioElement.preload = "auto";
  50251. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  50252. _this._isReadyToPlay = true;
  50253. if (_this.autoplay) {
  50254. _this.play();
  50255. }
  50256. if (_this._readyToPlayCallback) {
  50257. _this._readyToPlayCallback();
  50258. }
  50259. });
  50260. document.body.appendChild(this._htmlAudioElement);
  50261. }
  50262. break;
  50263. }
  50264. }
  50265. break;
  50266. default:
  50267. validParameter = false;
  50268. break;
  50269. }
  50270. if (!validParameter) {
  50271. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  50272. }
  50273. else {
  50274. if (!codecSupportedFound) {
  50275. this._isReadyToPlay = true;
  50276. // Simulating a ready to play event to avoid breaking code path
  50277. if (this._readyToPlayCallback) {
  50278. window.setTimeout(function () {
  50279. if (_this._readyToPlayCallback) {
  50280. _this._readyToPlayCallback();
  50281. }
  50282. }, 1000);
  50283. }
  50284. }
  50285. }
  50286. }
  50287. }
  50288. else {
  50289. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  50290. this._scene.mainSoundTrack.AddSound(this);
  50291. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  50292. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  50293. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  50294. }
  50295. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  50296. if (this._readyToPlayCallback) {
  50297. window.setTimeout(function () {
  50298. if (_this._readyToPlayCallback) {
  50299. _this._readyToPlayCallback();
  50300. }
  50301. }, 1000);
  50302. }
  50303. }
  50304. }
  50305. Sound.prototype.dispose = function () {
  50306. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  50307. if (this.isPlaying) {
  50308. this.stop();
  50309. }
  50310. this._isReadyToPlay = false;
  50311. if (this.soundTrackId === -1) {
  50312. this._scene.mainSoundTrack.RemoveSound(this);
  50313. }
  50314. else {
  50315. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  50316. }
  50317. if (this._soundGain) {
  50318. this._soundGain.disconnect();
  50319. this._soundGain = null;
  50320. }
  50321. if (this._soundPanner) {
  50322. this._soundPanner.disconnect();
  50323. this._soundPanner = null;
  50324. }
  50325. if (this._soundSource) {
  50326. this._soundSource.disconnect();
  50327. this._soundSource = null;
  50328. }
  50329. this._audioBuffer = null;
  50330. if (this._htmlAudioElement) {
  50331. this._htmlAudioElement.pause();
  50332. this._htmlAudioElement.src = "";
  50333. document.body.removeChild(this._htmlAudioElement);
  50334. }
  50335. if (this._connectedMesh && this._registerFunc) {
  50336. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  50337. this._connectedMesh = null;
  50338. }
  50339. }
  50340. };
  50341. Sound.prototype.isReady = function () {
  50342. return this._isReadyToPlay;
  50343. };
  50344. Sound.prototype._soundLoaded = function (audioData) {
  50345. var _this = this;
  50346. if (!BABYLON.Engine.audioEngine.audioContext) {
  50347. return;
  50348. }
  50349. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  50350. _this._audioBuffer = buffer;
  50351. _this._isReadyToPlay = true;
  50352. if (_this.autoplay) {
  50353. _this.play();
  50354. }
  50355. if (_this._readyToPlayCallback) {
  50356. _this._readyToPlayCallback();
  50357. }
  50358. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  50359. };
  50360. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  50361. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  50362. this._audioBuffer = audioBuffer;
  50363. this._isReadyToPlay = true;
  50364. }
  50365. };
  50366. Sound.prototype.updateOptions = function (options) {
  50367. if (options) {
  50368. this.loop = options.loop || this.loop;
  50369. this.maxDistance = options.maxDistance || this.maxDistance;
  50370. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  50371. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  50372. this.refDistance = options.refDistance || this.refDistance;
  50373. this.distanceModel = options.distanceModel || this.distanceModel;
  50374. this._playbackRate = options.playbackRate || this._playbackRate;
  50375. this._updateSpatialParameters();
  50376. if (this.isPlaying) {
  50377. if (this._streaming) {
  50378. this._htmlAudioElement.playbackRate = this._playbackRate;
  50379. }
  50380. else {
  50381. if (this._soundSource) {
  50382. this._soundSource.playbackRate.value = this._playbackRate;
  50383. }
  50384. }
  50385. }
  50386. }
  50387. };
  50388. Sound.prototype._createSpatialParameters = function () {
  50389. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  50390. if (this._scene.headphone) {
  50391. this._panningModel = "HRTF";
  50392. }
  50393. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  50394. this._updateSpatialParameters();
  50395. this._soundPanner.connect(this._ouputAudioNode);
  50396. this._inputAudioNode = this._soundPanner;
  50397. }
  50398. };
  50399. Sound.prototype._updateSpatialParameters = function () {
  50400. if (this.spatialSound && this._soundPanner) {
  50401. if (this.useCustomAttenuation) {
  50402. // Tricks to disable in a way embedded Web Audio attenuation
  50403. this._soundPanner.distanceModel = "linear";
  50404. this._soundPanner.maxDistance = Number.MAX_VALUE;
  50405. this._soundPanner.refDistance = 1;
  50406. this._soundPanner.rolloffFactor = 1;
  50407. this._soundPanner.panningModel = this._panningModel;
  50408. }
  50409. else {
  50410. this._soundPanner.distanceModel = this.distanceModel;
  50411. this._soundPanner.maxDistance = this.maxDistance;
  50412. this._soundPanner.refDistance = this.refDistance;
  50413. this._soundPanner.rolloffFactor = this.rolloffFactor;
  50414. this._soundPanner.panningModel = this._panningModel;
  50415. }
  50416. }
  50417. };
  50418. Sound.prototype.switchPanningModelToHRTF = function () {
  50419. this._panningModel = "HRTF";
  50420. this._switchPanningModel();
  50421. };
  50422. Sound.prototype.switchPanningModelToEqualPower = function () {
  50423. this._panningModel = "equalpower";
  50424. this._switchPanningModel();
  50425. };
  50426. Sound.prototype._switchPanningModel = function () {
  50427. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  50428. this._soundPanner.panningModel = this._panningModel;
  50429. }
  50430. };
  50431. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  50432. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  50433. if (this._isOutputConnected) {
  50434. this._ouputAudioNode.disconnect();
  50435. }
  50436. this._ouputAudioNode.connect(soundTrackAudioNode);
  50437. this._isOutputConnected = true;
  50438. }
  50439. };
  50440. /**
  50441. * Transform this sound into a directional source
  50442. * @param coneInnerAngle Size of the inner cone in degree
  50443. * @param coneOuterAngle Size of the outer cone in degree
  50444. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  50445. */
  50446. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  50447. if (coneOuterAngle < coneInnerAngle) {
  50448. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  50449. return;
  50450. }
  50451. this._coneInnerAngle = coneInnerAngle;
  50452. this._coneOuterAngle = coneOuterAngle;
  50453. this._coneOuterGain = coneOuterGain;
  50454. this._isDirectional = true;
  50455. if (this.isPlaying && this.loop) {
  50456. this.stop();
  50457. this.play();
  50458. }
  50459. };
  50460. Sound.prototype.setPosition = function (newPosition) {
  50461. this._position = newPosition;
  50462. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  50463. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  50464. }
  50465. };
  50466. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  50467. this._localDirection = newLocalDirection;
  50468. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  50469. this._updateDirection();
  50470. }
  50471. };
  50472. Sound.prototype._updateDirection = function () {
  50473. if (!this._connectedMesh || !this._soundPanner) {
  50474. return;
  50475. }
  50476. var mat = this._connectedMesh.getWorldMatrix();
  50477. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  50478. direction.normalize();
  50479. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  50480. };
  50481. Sound.prototype.updateDistanceFromListener = function () {
  50482. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  50483. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  50484. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  50485. }
  50486. };
  50487. Sound.prototype.setAttenuationFunction = function (callback) {
  50488. this._customAttenuationFunction = callback;
  50489. };
  50490. /**
  50491. * Play the sound
  50492. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  50493. * @param offset (optional) Start the sound setting it at a specific time
  50494. */
  50495. Sound.prototype.play = function (time, offset) {
  50496. var _this = this;
  50497. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  50498. try {
  50499. if (this._startOffset < 0) {
  50500. time = -this._startOffset;
  50501. this._startOffset = 0;
  50502. }
  50503. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  50504. if (!this._soundSource || !this._streamingSource) {
  50505. if (this.spatialSound && this._soundPanner) {
  50506. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  50507. if (this._isDirectional) {
  50508. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  50509. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  50510. this._soundPanner.coneOuterGain = this._coneOuterGain;
  50511. if (this._connectedMesh) {
  50512. this._updateDirection();
  50513. }
  50514. else {
  50515. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  50516. }
  50517. }
  50518. }
  50519. }
  50520. if (this._streaming) {
  50521. if (!this._streamingSource) {
  50522. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  50523. this._htmlAudioElement.onended = function () { _this._onended(); };
  50524. this._htmlAudioElement.playbackRate = this._playbackRate;
  50525. }
  50526. this._streamingSource.disconnect();
  50527. this._streamingSource.connect(this._inputAudioNode);
  50528. this._htmlAudioElement.play();
  50529. }
  50530. else {
  50531. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  50532. this._soundSource.buffer = this._audioBuffer;
  50533. this._soundSource.connect(this._inputAudioNode);
  50534. this._soundSource.loop = this.loop;
  50535. this._soundSource.playbackRate.value = this._playbackRate;
  50536. this._soundSource.onended = function () { _this._onended(); };
  50537. if (this._soundSource.buffer) {
  50538. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  50539. }
  50540. }
  50541. this._startTime = startTime;
  50542. this.isPlaying = true;
  50543. this.isPaused = false;
  50544. }
  50545. catch (ex) {
  50546. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  50547. }
  50548. }
  50549. };
  50550. Sound.prototype._onended = function () {
  50551. this.isPlaying = false;
  50552. if (this.onended) {
  50553. this.onended();
  50554. }
  50555. };
  50556. /**
  50557. * Stop the sound
  50558. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  50559. */
  50560. Sound.prototype.stop = function (time) {
  50561. if (this.isPlaying) {
  50562. if (this._streaming) {
  50563. this._htmlAudioElement.pause();
  50564. // Test needed for Firefox or it will generate an Invalid State Error
  50565. if (this._htmlAudioElement.currentTime > 0) {
  50566. this._htmlAudioElement.currentTime = 0;
  50567. }
  50568. }
  50569. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  50570. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  50571. this._soundSource.stop(stopTime);
  50572. this._soundSource.onended = function () { };
  50573. if (!this.isPaused) {
  50574. this._startOffset = 0;
  50575. }
  50576. }
  50577. this.isPlaying = false;
  50578. }
  50579. };
  50580. Sound.prototype.pause = function () {
  50581. if (this.isPlaying) {
  50582. this.isPaused = true;
  50583. if (this._streaming) {
  50584. this._htmlAudioElement.pause();
  50585. }
  50586. else if (BABYLON.Engine.audioEngine.audioContext) {
  50587. this.stop(0);
  50588. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  50589. }
  50590. }
  50591. };
  50592. Sound.prototype.setVolume = function (newVolume, time) {
  50593. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  50594. if (time && BABYLON.Engine.audioEngine.audioContext) {
  50595. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  50596. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  50597. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  50598. }
  50599. else {
  50600. this._soundGain.gain.value = newVolume;
  50601. }
  50602. }
  50603. this._volume = newVolume;
  50604. };
  50605. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  50606. this._playbackRate = newPlaybackRate;
  50607. if (this.isPlaying) {
  50608. if (this._streaming) {
  50609. this._htmlAudioElement.playbackRate = this._playbackRate;
  50610. }
  50611. else if (this._soundSource) {
  50612. this._soundSource.playbackRate.value = this._playbackRate;
  50613. }
  50614. }
  50615. };
  50616. Sound.prototype.getVolume = function () {
  50617. return this._volume;
  50618. };
  50619. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  50620. var _this = this;
  50621. if (this._connectedMesh && this._registerFunc) {
  50622. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  50623. this._registerFunc = null;
  50624. }
  50625. this._connectedMesh = meshToConnectTo;
  50626. if (!this.spatialSound) {
  50627. this.spatialSound = true;
  50628. this._createSpatialParameters();
  50629. if (this.isPlaying && this.loop) {
  50630. this.stop();
  50631. this.play();
  50632. }
  50633. }
  50634. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  50635. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  50636. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  50637. };
  50638. Sound.prototype.detachFromMesh = function () {
  50639. if (this._connectedMesh && this._registerFunc) {
  50640. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  50641. this._registerFunc = null;
  50642. this._connectedMesh = null;
  50643. }
  50644. };
  50645. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  50646. if (!node.getBoundingInfo) {
  50647. return;
  50648. }
  50649. var mesh = node;
  50650. var boundingInfo = mesh.getBoundingInfo();
  50651. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  50652. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  50653. this._updateDirection();
  50654. }
  50655. };
  50656. Sound.prototype.clone = function () {
  50657. var _this = this;
  50658. if (!this._streaming) {
  50659. var setBufferAndRun = function () {
  50660. if (_this._isReadyToPlay) {
  50661. clonedSound._audioBuffer = _this.getAudioBuffer();
  50662. clonedSound._isReadyToPlay = true;
  50663. if (clonedSound.autoplay) {
  50664. clonedSound.play();
  50665. }
  50666. }
  50667. else {
  50668. window.setTimeout(setBufferAndRun, 300);
  50669. }
  50670. };
  50671. var currentOptions = {
  50672. autoplay: this.autoplay, loop: this.loop,
  50673. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  50674. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  50675. refDistance: this.refDistance, distanceModel: this.distanceModel
  50676. };
  50677. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  50678. if (this.useCustomAttenuation) {
  50679. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  50680. }
  50681. clonedSound.setPosition(this._position);
  50682. clonedSound.setPlaybackRate(this._playbackRate);
  50683. setBufferAndRun();
  50684. return clonedSound;
  50685. }
  50686. else {
  50687. return null;
  50688. }
  50689. };
  50690. Sound.prototype.getAudioBuffer = function () {
  50691. return this._audioBuffer;
  50692. };
  50693. Sound.prototype.serialize = function () {
  50694. var serializationObject = {
  50695. name: this.name,
  50696. url: this.name,
  50697. autoplay: this.autoplay,
  50698. loop: this.loop,
  50699. volume: this._volume,
  50700. spatialSound: this.spatialSound,
  50701. maxDistance: this.maxDistance,
  50702. rolloffFactor: this.rolloffFactor,
  50703. refDistance: this.refDistance,
  50704. distanceModel: this.distanceModel,
  50705. playbackRate: this._playbackRate,
  50706. panningModel: this._panningModel,
  50707. soundTrackId: this.soundTrackId
  50708. };
  50709. if (this.spatialSound) {
  50710. if (this._connectedMesh)
  50711. serializationObject.connectedMeshId = this._connectedMesh.id;
  50712. serializationObject.position = this._position.asArray();
  50713. serializationObject.refDistance = this.refDistance;
  50714. serializationObject.distanceModel = this.distanceModel;
  50715. serializationObject.isDirectional = this._isDirectional;
  50716. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  50717. serializationObject.coneInnerAngle = this._coneInnerAngle;
  50718. serializationObject.coneOuterAngle = this._coneOuterAngle;
  50719. serializationObject.coneOuterGain = this._coneOuterGain;
  50720. }
  50721. return serializationObject;
  50722. };
  50723. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  50724. var soundName = parsedSound.name;
  50725. var soundUrl;
  50726. if (parsedSound.url) {
  50727. soundUrl = rootUrl + parsedSound.url;
  50728. }
  50729. else {
  50730. soundUrl = rootUrl + soundName;
  50731. }
  50732. var options = {
  50733. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  50734. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  50735. rolloffFactor: parsedSound.rolloffFactor,
  50736. refDistance: parsedSound.refDistance,
  50737. distanceModel: parsedSound.distanceModel,
  50738. playbackRate: parsedSound.playbackRate
  50739. };
  50740. var newSound;
  50741. if (!sourceSound) {
  50742. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  50743. scene._addPendingData(newSound);
  50744. }
  50745. else {
  50746. var setBufferAndRun = function () {
  50747. if (sourceSound._isReadyToPlay) {
  50748. newSound._audioBuffer = sourceSound.getAudioBuffer();
  50749. newSound._isReadyToPlay = true;
  50750. if (newSound.autoplay) {
  50751. newSound.play();
  50752. }
  50753. }
  50754. else {
  50755. window.setTimeout(setBufferAndRun, 300);
  50756. }
  50757. };
  50758. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  50759. setBufferAndRun();
  50760. }
  50761. if (parsedSound.position) {
  50762. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  50763. newSound.setPosition(soundPosition);
  50764. }
  50765. if (parsedSound.isDirectional) {
  50766. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  50767. if (parsedSound.localDirectionToMesh) {
  50768. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  50769. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  50770. }
  50771. }
  50772. if (parsedSound.connectedMeshId) {
  50773. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  50774. if (connectedMesh) {
  50775. newSound.attachToMesh(connectedMesh);
  50776. }
  50777. }
  50778. return newSound;
  50779. };
  50780. return Sound;
  50781. }());
  50782. BABYLON.Sound = Sound;
  50783. })(BABYLON || (BABYLON = {}));
  50784. //# sourceMappingURL=babylon.sound.js.map
  50785. var BABYLON;
  50786. (function (BABYLON) {
  50787. var SoundTrack = /** @class */ (function () {
  50788. function SoundTrack(scene, options) {
  50789. this.id = -1;
  50790. this._isMainTrack = false;
  50791. this._isInitialized = false;
  50792. this._scene = scene;
  50793. this.soundCollection = new Array();
  50794. this._options = options;
  50795. if (!this._isMainTrack) {
  50796. this._scene.soundTracks.push(this);
  50797. this.id = this._scene.soundTracks.length - 1;
  50798. }
  50799. }
  50800. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  50801. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  50802. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  50803. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  50804. if (this._options) {
  50805. if (this._options.volume) {
  50806. this._outputAudioNode.gain.value = this._options.volume;
  50807. }
  50808. if (this._options.mainTrack) {
  50809. this._isMainTrack = this._options.mainTrack;
  50810. }
  50811. }
  50812. this._isInitialized = true;
  50813. }
  50814. };
  50815. SoundTrack.prototype.dispose = function () {
  50816. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  50817. if (this._connectedAnalyser) {
  50818. this._connectedAnalyser.stopDebugCanvas();
  50819. }
  50820. while (this.soundCollection.length) {
  50821. this.soundCollection[0].dispose();
  50822. }
  50823. if (this._outputAudioNode) {
  50824. this._outputAudioNode.disconnect();
  50825. }
  50826. this._outputAudioNode = null;
  50827. }
  50828. };
  50829. SoundTrack.prototype.AddSound = function (sound) {
  50830. if (!this._isInitialized) {
  50831. this._initializeSoundTrackAudioGraph();
  50832. }
  50833. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  50834. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  50835. }
  50836. if (sound.soundTrackId) {
  50837. if (sound.soundTrackId === -1) {
  50838. this._scene.mainSoundTrack.RemoveSound(sound);
  50839. }
  50840. else {
  50841. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  50842. }
  50843. }
  50844. this.soundCollection.push(sound);
  50845. sound.soundTrackId = this.id;
  50846. };
  50847. SoundTrack.prototype.RemoveSound = function (sound) {
  50848. var index = this.soundCollection.indexOf(sound);
  50849. if (index !== -1) {
  50850. this.soundCollection.splice(index, 1);
  50851. }
  50852. };
  50853. SoundTrack.prototype.setVolume = function (newVolume) {
  50854. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  50855. this._outputAudioNode.gain.value = newVolume;
  50856. }
  50857. };
  50858. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  50859. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  50860. for (var i = 0; i < this.soundCollection.length; i++) {
  50861. this.soundCollection[i].switchPanningModelToHRTF();
  50862. }
  50863. }
  50864. };
  50865. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  50866. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  50867. for (var i = 0; i < this.soundCollection.length; i++) {
  50868. this.soundCollection[i].switchPanningModelToEqualPower();
  50869. }
  50870. }
  50871. };
  50872. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  50873. if (this._connectedAnalyser) {
  50874. this._connectedAnalyser.stopDebugCanvas();
  50875. }
  50876. this._connectedAnalyser = analyser;
  50877. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  50878. this._outputAudioNode.disconnect();
  50879. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  50880. }
  50881. };
  50882. return SoundTrack;
  50883. }());
  50884. BABYLON.SoundTrack = SoundTrack;
  50885. })(BABYLON || (BABYLON = {}));
  50886. //# sourceMappingURL=babylon.soundtrack.js.map
  50887. var BABYLON;
  50888. (function (BABYLON) {
  50889. var Analyser = /** @class */ (function () {
  50890. function Analyser(scene) {
  50891. this.SMOOTHING = 0.75;
  50892. this.FFT_SIZE = 512;
  50893. this.BARGRAPHAMPLITUDE = 256;
  50894. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  50895. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  50896. this._scene = scene;
  50897. this._audioEngine = BABYLON.Engine.audioEngine;
  50898. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  50899. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  50900. this._webAudioAnalyser.minDecibels = -140;
  50901. this._webAudioAnalyser.maxDecibels = 0;
  50902. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  50903. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  50904. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  50905. }
  50906. }
  50907. Analyser.prototype.getFrequencyBinCount = function () {
  50908. if (this._audioEngine.canUseWebAudio) {
  50909. return this._webAudioAnalyser.frequencyBinCount;
  50910. }
  50911. else {
  50912. return 0;
  50913. }
  50914. };
  50915. Analyser.prototype.getByteFrequencyData = function () {
  50916. if (this._audioEngine.canUseWebAudio) {
  50917. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  50918. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  50919. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  50920. }
  50921. return this._byteFreqs;
  50922. };
  50923. Analyser.prototype.getByteTimeDomainData = function () {
  50924. if (this._audioEngine.canUseWebAudio) {
  50925. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  50926. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  50927. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  50928. }
  50929. return this._byteTime;
  50930. };
  50931. Analyser.prototype.getFloatFrequencyData = function () {
  50932. if (this._audioEngine.canUseWebAudio) {
  50933. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  50934. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  50935. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  50936. }
  50937. return this._floatFreqs;
  50938. };
  50939. Analyser.prototype.drawDebugCanvas = function () {
  50940. var _this = this;
  50941. if (this._audioEngine.canUseWebAudio) {
  50942. if (!this._debugCanvas) {
  50943. this._debugCanvas = document.createElement("canvas");
  50944. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  50945. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  50946. this._debugCanvas.style.position = "absolute";
  50947. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  50948. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  50949. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  50950. document.body.appendChild(this._debugCanvas);
  50951. this._registerFunc = function () {
  50952. _this.drawDebugCanvas();
  50953. };
  50954. this._scene.registerBeforeRender(this._registerFunc);
  50955. }
  50956. if (this._registerFunc && this._debugCanvasContext) {
  50957. var workingArray = this.getByteFrequencyData();
  50958. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  50959. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  50960. // Draw the frequency domain chart.
  50961. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  50962. var value = workingArray[i];
  50963. var percent = value / this.BARGRAPHAMPLITUDE;
  50964. var height = this.DEBUGCANVASSIZE.height * percent;
  50965. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  50966. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  50967. var hue = i / this.getFrequencyBinCount() * 360;
  50968. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  50969. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  50970. }
  50971. }
  50972. }
  50973. };
  50974. Analyser.prototype.stopDebugCanvas = function () {
  50975. if (this._debugCanvas) {
  50976. if (this._registerFunc) {
  50977. this._scene.unregisterBeforeRender(this._registerFunc);
  50978. this._registerFunc = null;
  50979. }
  50980. document.body.removeChild(this._debugCanvas);
  50981. this._debugCanvas = null;
  50982. this._debugCanvasContext = null;
  50983. }
  50984. };
  50985. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  50986. if (this._audioEngine.canUseWebAudio) {
  50987. inputAudioNode.connect(this._webAudioAnalyser);
  50988. this._webAudioAnalyser.connect(outputAudioNode);
  50989. }
  50990. };
  50991. Analyser.prototype.dispose = function () {
  50992. if (this._audioEngine.canUseWebAudio) {
  50993. this._webAudioAnalyser.disconnect();
  50994. }
  50995. };
  50996. return Analyser;
  50997. }());
  50998. BABYLON.Analyser = Analyser;
  50999. })(BABYLON || (BABYLON = {}));
  51000. //# sourceMappingURL=babylon.analyser.js.map
  51001. var BABYLON;
  51002. (function (BABYLON) {
  51003. var CubeTexture = /** @class */ (function (_super) {
  51004. __extends(CubeTexture, _super);
  51005. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  51006. if (extensions === void 0) { extensions = null; }
  51007. if (noMipmap === void 0) { noMipmap = false; }
  51008. if (files === void 0) { files = null; }
  51009. if (onLoad === void 0) { onLoad = null; }
  51010. if (onError === void 0) { onError = null; }
  51011. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  51012. if (prefiltered === void 0) { prefiltered = false; }
  51013. if (forcedExtension === void 0) { forcedExtension = null; }
  51014. var _this = _super.call(this, scene) || this;
  51015. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  51016. _this.name = rootUrl;
  51017. _this.url = rootUrl;
  51018. _this._noMipmap = noMipmap;
  51019. _this.hasAlpha = false;
  51020. _this._format = format;
  51021. _this._prefiltered = prefiltered;
  51022. _this.isCube = true;
  51023. _this._textureMatrix = BABYLON.Matrix.Identity();
  51024. if (prefiltered) {
  51025. _this.gammaSpace = false;
  51026. }
  51027. if (!rootUrl && !files) {
  51028. return _this;
  51029. }
  51030. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  51031. var lastDot = rootUrl.lastIndexOf(".");
  51032. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  51033. var isDDS = (extension === ".dds");
  51034. if (!files) {
  51035. if (!isDDS && !extensions) {
  51036. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  51037. }
  51038. files = [];
  51039. if (extensions) {
  51040. for (var index = 0; index < extensions.length; index++) {
  51041. files.push(rootUrl + extensions[index]);
  51042. }
  51043. }
  51044. }
  51045. _this._files = files;
  51046. if (!_this._texture) {
  51047. if (!scene.useDelayedTextureLoading) {
  51048. if (prefiltered) {
  51049. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  51050. }
  51051. else {
  51052. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  51053. }
  51054. }
  51055. else {
  51056. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  51057. }
  51058. }
  51059. else if (onLoad) {
  51060. if (_this._texture.isReady) {
  51061. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  51062. }
  51063. else {
  51064. _this._texture.onLoadedObservable.add(onLoad);
  51065. }
  51066. }
  51067. return _this;
  51068. }
  51069. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  51070. return new CubeTexture("", scene, null, noMipmap, files);
  51071. };
  51072. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  51073. if (forcedExtension === void 0) { forcedExtension = null; }
  51074. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  51075. };
  51076. // Methods
  51077. CubeTexture.prototype.delayLoad = function () {
  51078. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  51079. return;
  51080. }
  51081. var scene = this.getScene();
  51082. if (!scene) {
  51083. return;
  51084. }
  51085. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  51086. this._texture = this._getFromCache(this.url, this._noMipmap);
  51087. if (!this._texture) {
  51088. if (this._prefiltered) {
  51089. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  51090. }
  51091. else {
  51092. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  51093. }
  51094. }
  51095. };
  51096. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  51097. return this._textureMatrix;
  51098. };
  51099. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  51100. this._textureMatrix = value;
  51101. };
  51102. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  51103. var texture = BABYLON.SerializationHelper.Parse(function () {
  51104. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  51105. }, parsedTexture, scene);
  51106. // Animations
  51107. if (parsedTexture.animations) {
  51108. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  51109. var parsedAnimation = parsedTexture.animations[animationIndex];
  51110. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  51111. }
  51112. }
  51113. return texture;
  51114. };
  51115. CubeTexture.prototype.clone = function () {
  51116. var _this = this;
  51117. return BABYLON.SerializationHelper.Clone(function () {
  51118. var scene = _this.getScene();
  51119. if (!scene) {
  51120. return _this;
  51121. }
  51122. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  51123. }, this);
  51124. };
  51125. return CubeTexture;
  51126. }(BABYLON.BaseTexture));
  51127. BABYLON.CubeTexture = CubeTexture;
  51128. })(BABYLON || (BABYLON = {}));
  51129. //# sourceMappingURL=babylon.cubeTexture.js.map
  51130. var BABYLON;
  51131. (function (BABYLON) {
  51132. var RenderTargetTexture = /** @class */ (function (_super) {
  51133. __extends(RenderTargetTexture, _super);
  51134. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  51135. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  51136. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  51137. if (isCube === void 0) { isCube = false; }
  51138. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  51139. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  51140. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  51141. if (isMulti === void 0) { isMulti = false; }
  51142. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  51143. _this.isCube = isCube;
  51144. /**
  51145. * Use this list to define the list of mesh you want to render.
  51146. */
  51147. _this.renderList = new Array();
  51148. _this.renderParticles = true;
  51149. _this.renderSprites = false;
  51150. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  51151. _this.ignoreCameraViewport = false;
  51152. // Events
  51153. /**
  51154. * An event triggered when the texture is unbind.
  51155. * @type {BABYLON.Observable}
  51156. */
  51157. _this.onBeforeBindObservable = new BABYLON.Observable();
  51158. /**
  51159. * An event triggered when the texture is unbind.
  51160. * @type {BABYLON.Observable}
  51161. */
  51162. _this.onAfterUnbindObservable = new BABYLON.Observable();
  51163. /**
  51164. * An event triggered before rendering the texture
  51165. * @type {BABYLON.Observable}
  51166. */
  51167. _this.onBeforeRenderObservable = new BABYLON.Observable();
  51168. /**
  51169. * An event triggered after rendering the texture
  51170. * @type {BABYLON.Observable}
  51171. */
  51172. _this.onAfterRenderObservable = new BABYLON.Observable();
  51173. /**
  51174. * An event triggered after the texture clear
  51175. * @type {BABYLON.Observable}
  51176. */
  51177. _this.onClearObservable = new BABYLON.Observable();
  51178. _this._currentRefreshId = -1;
  51179. _this._refreshRate = 1;
  51180. _this._samples = 1;
  51181. scene = _this.getScene();
  51182. if (!scene) {
  51183. return _this;
  51184. }
  51185. _this._engine = scene.getEngine();
  51186. _this.name = name;
  51187. _this.isRenderTarget = true;
  51188. _this._initialSizeParameter = size;
  51189. _this._processSizeParameter(size);
  51190. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  51191. });
  51192. _this._generateMipMaps = generateMipMaps ? true : false;
  51193. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  51194. // Rendering groups
  51195. _this._renderingManager = new BABYLON.RenderingManager(scene);
  51196. if (isMulti) {
  51197. return _this;
  51198. }
  51199. _this._renderTargetOptions = {
  51200. generateMipMaps: generateMipMaps,
  51201. type: type,
  51202. samplingMode: samplingMode,
  51203. generateDepthBuffer: generateDepthBuffer,
  51204. generateStencilBuffer: generateStencilBuffer
  51205. };
  51206. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  51207. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51208. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51209. }
  51210. if (isCube) {
  51211. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  51212. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  51213. _this._textureMatrix = BABYLON.Matrix.Identity();
  51214. }
  51215. else {
  51216. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  51217. }
  51218. return _this;
  51219. }
  51220. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  51221. get: function () {
  51222. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  51223. },
  51224. enumerable: true,
  51225. configurable: true
  51226. });
  51227. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  51228. get: function () {
  51229. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  51230. },
  51231. enumerable: true,
  51232. configurable: true
  51233. });
  51234. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  51235. get: function () {
  51236. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  51237. },
  51238. enumerable: true,
  51239. configurable: true
  51240. });
  51241. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  51242. set: function (callback) {
  51243. if (this._onAfterUnbindObserver) {
  51244. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  51245. }
  51246. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  51247. },
  51248. enumerable: true,
  51249. configurable: true
  51250. });
  51251. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  51252. set: function (callback) {
  51253. if (this._onBeforeRenderObserver) {
  51254. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  51255. }
  51256. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  51257. },
  51258. enumerable: true,
  51259. configurable: true
  51260. });
  51261. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  51262. set: function (callback) {
  51263. if (this._onAfterRenderObserver) {
  51264. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  51265. }
  51266. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  51267. },
  51268. enumerable: true,
  51269. configurable: true
  51270. });
  51271. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  51272. set: function (callback) {
  51273. if (this._onClearObserver) {
  51274. this.onClearObservable.remove(this._onClearObserver);
  51275. }
  51276. this._onClearObserver = this.onClearObservable.add(callback);
  51277. },
  51278. enumerable: true,
  51279. configurable: true
  51280. });
  51281. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  51282. get: function () {
  51283. return this._renderTargetOptions;
  51284. },
  51285. enumerable: true,
  51286. configurable: true
  51287. });
  51288. RenderTargetTexture.prototype._onRatioRescale = function () {
  51289. if (this._sizeRatio) {
  51290. this.resize(this._initialSizeParameter);
  51291. }
  51292. };
  51293. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  51294. if (size.ratio) {
  51295. this._sizeRatio = size.ratio;
  51296. this._size = {
  51297. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  51298. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  51299. };
  51300. }
  51301. else {
  51302. this._size = size;
  51303. }
  51304. };
  51305. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  51306. get: function () {
  51307. return this._samples;
  51308. },
  51309. set: function (value) {
  51310. if (this._samples === value) {
  51311. return;
  51312. }
  51313. var scene = this.getScene();
  51314. if (!scene) {
  51315. return;
  51316. }
  51317. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  51318. },
  51319. enumerable: true,
  51320. configurable: true
  51321. });
  51322. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  51323. this._currentRefreshId = -1;
  51324. };
  51325. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  51326. get: function () {
  51327. return this._refreshRate;
  51328. },
  51329. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  51330. set: function (value) {
  51331. this._refreshRate = value;
  51332. this.resetRefreshCounter();
  51333. },
  51334. enumerable: true,
  51335. configurable: true
  51336. });
  51337. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  51338. if (!this._postProcessManager) {
  51339. var scene = this.getScene();
  51340. if (!scene) {
  51341. return;
  51342. }
  51343. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  51344. this._postProcesses = new Array();
  51345. }
  51346. this._postProcesses.push(postProcess);
  51347. this._postProcesses[0].autoClear = false;
  51348. };
  51349. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  51350. if (!this._postProcesses) {
  51351. return;
  51352. }
  51353. if (dispose) {
  51354. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  51355. var postProcess = _a[_i];
  51356. postProcess.dispose();
  51357. }
  51358. }
  51359. this._postProcesses = [];
  51360. };
  51361. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  51362. if (!this._postProcesses) {
  51363. return;
  51364. }
  51365. var index = this._postProcesses.indexOf(postProcess);
  51366. if (index === -1) {
  51367. return;
  51368. }
  51369. this._postProcesses.splice(index, 1);
  51370. if (this._postProcesses.length > 0) {
  51371. this._postProcesses[0].autoClear = false;
  51372. }
  51373. };
  51374. RenderTargetTexture.prototype._shouldRender = function () {
  51375. if (this._currentRefreshId === -1) {
  51376. this._currentRefreshId = 1;
  51377. return true;
  51378. }
  51379. if (this.refreshRate === this._currentRefreshId) {
  51380. this._currentRefreshId = 1;
  51381. return true;
  51382. }
  51383. this._currentRefreshId++;
  51384. return false;
  51385. };
  51386. RenderTargetTexture.prototype.getRenderSize = function () {
  51387. if (this._size.width) {
  51388. return this._size.width;
  51389. }
  51390. return this._size;
  51391. };
  51392. RenderTargetTexture.prototype.getRenderWidth = function () {
  51393. if (this._size.width) {
  51394. return this._size.width;
  51395. }
  51396. return this._size;
  51397. };
  51398. RenderTargetTexture.prototype.getRenderHeight = function () {
  51399. if (this._size.width) {
  51400. return this._size.height;
  51401. }
  51402. return this._size;
  51403. };
  51404. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  51405. get: function () {
  51406. return true;
  51407. },
  51408. enumerable: true,
  51409. configurable: true
  51410. });
  51411. RenderTargetTexture.prototype.scale = function (ratio) {
  51412. var newSize = this.getRenderSize() * ratio;
  51413. this.resize(newSize);
  51414. };
  51415. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  51416. if (this.isCube) {
  51417. return this._textureMatrix;
  51418. }
  51419. return _super.prototype.getReflectionTextureMatrix.call(this);
  51420. };
  51421. RenderTargetTexture.prototype.resize = function (size) {
  51422. this.releaseInternalTexture();
  51423. var scene = this.getScene();
  51424. if (!scene) {
  51425. return;
  51426. }
  51427. this._processSizeParameter(size);
  51428. if (this.isCube) {
  51429. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  51430. }
  51431. else {
  51432. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  51433. }
  51434. };
  51435. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  51436. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  51437. if (dumpForDebug === void 0) { dumpForDebug = false; }
  51438. var scene = this.getScene();
  51439. if (!scene) {
  51440. return;
  51441. }
  51442. var engine = scene.getEngine();
  51443. if (this.useCameraPostProcesses !== undefined) {
  51444. useCameraPostProcess = this.useCameraPostProcesses;
  51445. }
  51446. if (this._waitingRenderList) {
  51447. this.renderList = [];
  51448. for (var index = 0; index < this._waitingRenderList.length; index++) {
  51449. var id = this._waitingRenderList[index];
  51450. var mesh_1 = scene.getMeshByID(id);
  51451. if (mesh_1) {
  51452. this.renderList.push(mesh_1);
  51453. }
  51454. }
  51455. delete this._waitingRenderList;
  51456. }
  51457. // Is predicate defined?
  51458. if (this.renderListPredicate) {
  51459. if (this.renderList) {
  51460. this.renderList.splice(0); // Clear previous renderList
  51461. }
  51462. else {
  51463. this.renderList = [];
  51464. }
  51465. var scene = this.getScene();
  51466. if (!scene) {
  51467. return;
  51468. }
  51469. var sceneMeshes = scene.meshes;
  51470. for (var index = 0; index < sceneMeshes.length; index++) {
  51471. var mesh = sceneMeshes[index];
  51472. if (this.renderListPredicate(mesh)) {
  51473. this.renderList.push(mesh);
  51474. }
  51475. }
  51476. }
  51477. this.onBeforeBindObservable.notifyObservers(this);
  51478. // Set custom projection.
  51479. // Needs to be before binding to prevent changing the aspect ratio.
  51480. var camera;
  51481. if (this.activeCamera) {
  51482. camera = this.activeCamera;
  51483. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  51484. if (this.activeCamera !== scene.activeCamera) {
  51485. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  51486. }
  51487. }
  51488. else {
  51489. camera = scene.activeCamera;
  51490. if (camera) {
  51491. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  51492. }
  51493. }
  51494. // Prepare renderingManager
  51495. this._renderingManager.reset();
  51496. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  51497. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  51498. var sceneRenderId = scene.getRenderId();
  51499. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  51500. var mesh = currentRenderList[meshIndex];
  51501. if (mesh) {
  51502. if (!mesh.isReady()) {
  51503. // Reset _currentRefreshId
  51504. this.resetRefreshCounter();
  51505. continue;
  51506. }
  51507. mesh._preActivateForIntermediateRendering(sceneRenderId);
  51508. var isMasked = void 0;
  51509. if (!this.renderList && camera) {
  51510. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  51511. }
  51512. else {
  51513. isMasked = false;
  51514. }
  51515. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  51516. mesh._activate(sceneRenderId);
  51517. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  51518. var subMesh = mesh.subMeshes[subIndex];
  51519. scene._activeIndices.addCount(subMesh.indexCount, false);
  51520. this._renderingManager.dispatch(subMesh, mesh);
  51521. }
  51522. }
  51523. }
  51524. }
  51525. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  51526. var particleSystem = scene.particleSystems[particleIndex];
  51527. var emitter = particleSystem.emitter;
  51528. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  51529. continue;
  51530. }
  51531. if (currentRenderList.indexOf(emitter) >= 0) {
  51532. this._renderingManager.dispatchParticles(particleSystem);
  51533. }
  51534. }
  51535. if (this.isCube) {
  51536. for (var face = 0; face < 6; face++) {
  51537. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  51538. scene.incrementRenderId();
  51539. scene.resetCachedMaterial();
  51540. }
  51541. }
  51542. else {
  51543. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  51544. }
  51545. this.onAfterUnbindObservable.notifyObservers(this);
  51546. if (scene.activeCamera) {
  51547. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  51548. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  51549. }
  51550. engine.setViewport(scene.activeCamera.viewport);
  51551. }
  51552. scene.resetCachedMaterial();
  51553. };
  51554. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  51555. var minimum = 128;
  51556. var x = renderDimension * scale;
  51557. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  51558. // Ensure we don't exceed the render dimension (while staying POT)
  51559. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  51560. };
  51561. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  51562. var _this = this;
  51563. if (!this._texture) {
  51564. return;
  51565. }
  51566. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  51567. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  51568. });
  51569. };
  51570. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  51571. var scene = this.getScene();
  51572. if (!scene) {
  51573. return;
  51574. }
  51575. var engine = scene.getEngine();
  51576. if (!this._texture) {
  51577. return;
  51578. }
  51579. // Bind
  51580. if (this._postProcessManager) {
  51581. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  51582. }
  51583. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  51584. if (this._texture) {
  51585. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport);
  51586. }
  51587. }
  51588. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  51589. // Clear
  51590. if (this.onClearObservable.hasObservers()) {
  51591. this.onClearObservable.notifyObservers(engine);
  51592. }
  51593. else {
  51594. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  51595. }
  51596. if (!this._doNotChangeAspectRatio) {
  51597. scene.updateTransformMatrix(true);
  51598. }
  51599. // Render
  51600. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  51601. if (this._postProcessManager) {
  51602. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  51603. }
  51604. else if (useCameraPostProcess) {
  51605. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  51606. }
  51607. if (!this._doNotChangeAspectRatio) {
  51608. scene.updateTransformMatrix(true);
  51609. }
  51610. // Dump ?
  51611. if (dumpForDebug) {
  51612. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  51613. }
  51614. // Unbind
  51615. if (!this.isCube || faceIndex === 5) {
  51616. if (this.isCube) {
  51617. if (faceIndex === 5) {
  51618. engine.generateMipMapsForCubemap(this._texture);
  51619. }
  51620. }
  51621. this.unbindFrameBuffer(engine, faceIndex);
  51622. }
  51623. else {
  51624. this.onAfterRenderObservable.notifyObservers(faceIndex);
  51625. }
  51626. };
  51627. /**
  51628. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  51629. * This allowed control for front to back rendering or reversly depending of the special needs.
  51630. *
  51631. * @param renderingGroupId The rendering group id corresponding to its index
  51632. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  51633. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  51634. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  51635. */
  51636. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  51637. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  51638. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  51639. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  51640. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  51641. };
  51642. /**
  51643. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  51644. *
  51645. * @param renderingGroupId The rendering group id corresponding to its index
  51646. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  51647. */
  51648. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  51649. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  51650. };
  51651. RenderTargetTexture.prototype.clone = function () {
  51652. var textureSize = this.getSize();
  51653. 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);
  51654. // Base texture
  51655. newTexture.hasAlpha = this.hasAlpha;
  51656. newTexture.level = this.level;
  51657. // RenderTarget Texture
  51658. newTexture.coordinatesMode = this.coordinatesMode;
  51659. if (this.renderList) {
  51660. newTexture.renderList = this.renderList.slice(0);
  51661. }
  51662. return newTexture;
  51663. };
  51664. RenderTargetTexture.prototype.serialize = function () {
  51665. if (!this.name) {
  51666. return null;
  51667. }
  51668. var serializationObject = _super.prototype.serialize.call(this);
  51669. serializationObject.renderTargetSize = this.getRenderSize();
  51670. serializationObject.renderList = [];
  51671. if (this.renderList) {
  51672. for (var index = 0; index < this.renderList.length; index++) {
  51673. serializationObject.renderList.push(this.renderList[index].id);
  51674. }
  51675. }
  51676. return serializationObject;
  51677. };
  51678. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  51679. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  51680. var objBuffer = this.getInternalTexture();
  51681. var scene = this.getScene();
  51682. if (objBuffer && scene) {
  51683. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  51684. }
  51685. };
  51686. RenderTargetTexture.prototype.dispose = function () {
  51687. if (this._postProcessManager) {
  51688. this._postProcessManager.dispose();
  51689. this._postProcessManager = null;
  51690. }
  51691. this.clearPostProcesses(true);
  51692. if (this._resizeObserver) {
  51693. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  51694. this._resizeObserver = null;
  51695. }
  51696. this.renderList = null;
  51697. // Remove from custom render targets
  51698. var scene = this.getScene();
  51699. if (!scene) {
  51700. return;
  51701. }
  51702. var index = scene.customRenderTargets.indexOf(this);
  51703. if (index >= 0) {
  51704. scene.customRenderTargets.splice(index, 1);
  51705. }
  51706. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  51707. var camera = _a[_i];
  51708. index = camera.customRenderTargets.indexOf(this);
  51709. if (index >= 0) {
  51710. camera.customRenderTargets.splice(index, 1);
  51711. }
  51712. }
  51713. _super.prototype.dispose.call(this);
  51714. };
  51715. RenderTargetTexture.prototype._rebuild = function () {
  51716. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  51717. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  51718. }
  51719. if (this._postProcessManager) {
  51720. this._postProcessManager._rebuild();
  51721. }
  51722. };
  51723. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  51724. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  51725. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  51726. return RenderTargetTexture;
  51727. }(BABYLON.Texture));
  51728. BABYLON.RenderTargetTexture = RenderTargetTexture;
  51729. })(BABYLON || (BABYLON = {}));
  51730. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  51731. var BABYLON;
  51732. (function (BABYLON) {
  51733. ;
  51734. var MultiRenderTarget = /** @class */ (function (_super) {
  51735. __extends(MultiRenderTarget, _super);
  51736. function MultiRenderTarget(name, size, count, scene, options) {
  51737. var _this = this;
  51738. options = options || {};
  51739. var generateMipMaps = options.generateMipMaps ? options.generateMipMaps : false;
  51740. var generateDepthTexture = options.generateDepthTexture ? options.generateDepthTexture : false;
  51741. var doNotChangeAspectRatio = options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  51742. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  51743. _this._engine = scene.getEngine();
  51744. if (!_this.isSupported) {
  51745. _this.dispose();
  51746. return;
  51747. }
  51748. var types = [];
  51749. var samplingModes = [];
  51750. for (var i = 0; i < count; i++) {
  51751. if (options.types && options.types[i] !== undefined) {
  51752. types.push(options.types[i]);
  51753. }
  51754. else {
  51755. types.push(BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  51756. }
  51757. if (options.samplingModes && options.samplingModes[i] !== undefined) {
  51758. samplingModes.push(options.samplingModes[i]);
  51759. }
  51760. else {
  51761. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  51762. }
  51763. }
  51764. var generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  51765. var generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  51766. _this._size = size;
  51767. _this._multiRenderTargetOptions = {
  51768. samplingModes: samplingModes,
  51769. generateMipMaps: generateMipMaps,
  51770. generateDepthBuffer: generateDepthBuffer,
  51771. generateStencilBuffer: generateStencilBuffer,
  51772. generateDepthTexture: generateDepthTexture,
  51773. types: types,
  51774. textureCount: count
  51775. };
  51776. _this._createInternalTextures();
  51777. _this._createTextures();
  51778. return _this;
  51779. }
  51780. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  51781. get: function () {
  51782. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  51783. },
  51784. enumerable: true,
  51785. configurable: true
  51786. });
  51787. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  51788. get: function () {
  51789. return this._textures;
  51790. },
  51791. enumerable: true,
  51792. configurable: true
  51793. });
  51794. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  51795. get: function () {
  51796. return this._textures[this._textures.length - 1];
  51797. },
  51798. enumerable: true,
  51799. configurable: true
  51800. });
  51801. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  51802. set: function (wrap) {
  51803. if (this._textures) {
  51804. for (var i = 0; i < this._textures.length; i++) {
  51805. this._textures[i].wrapU = wrap;
  51806. }
  51807. }
  51808. },
  51809. enumerable: true,
  51810. configurable: true
  51811. });
  51812. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  51813. set: function (wrap) {
  51814. if (this._textures) {
  51815. for (var i = 0; i < this._textures.length; i++) {
  51816. this._textures[i].wrapV = wrap;
  51817. }
  51818. }
  51819. },
  51820. enumerable: true,
  51821. configurable: true
  51822. });
  51823. MultiRenderTarget.prototype._rebuild = function () {
  51824. this.releaseInternalTextures();
  51825. this._createInternalTextures();
  51826. for (var i = 0; i < this._internalTextures.length; i++) {
  51827. var texture = this._textures[i];
  51828. texture._texture = this._internalTextures[i];
  51829. }
  51830. // Keeps references to frame buffer and stencil/depth buffer
  51831. this._texture = this._internalTextures[0];
  51832. };
  51833. MultiRenderTarget.prototype._createInternalTextures = function () {
  51834. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  51835. };
  51836. MultiRenderTarget.prototype._createTextures = function () {
  51837. this._textures = [];
  51838. for (var i = 0; i < this._internalTextures.length; i++) {
  51839. var texture = new BABYLON.Texture(null, this.getScene());
  51840. texture._texture = this._internalTextures[i];
  51841. this._textures.push(texture);
  51842. }
  51843. // Keeps references to frame buffer and stencil/depth buffer
  51844. this._texture = this._internalTextures[0];
  51845. };
  51846. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  51847. get: function () {
  51848. return this._samples;
  51849. },
  51850. set: function (value) {
  51851. if (this._samples === value) {
  51852. return;
  51853. }
  51854. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  51855. },
  51856. enumerable: true,
  51857. configurable: true
  51858. });
  51859. MultiRenderTarget.prototype.resize = function (size) {
  51860. this.releaseInternalTextures();
  51861. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  51862. this._createInternalTextures();
  51863. };
  51864. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  51865. var _this = this;
  51866. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  51867. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  51868. });
  51869. };
  51870. MultiRenderTarget.prototype.dispose = function () {
  51871. this.releaseInternalTextures();
  51872. _super.prototype.dispose.call(this);
  51873. };
  51874. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  51875. if (!this._internalTextures) {
  51876. return;
  51877. }
  51878. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  51879. if (this._internalTextures[i] !== undefined) {
  51880. this._internalTextures[i].dispose();
  51881. this._internalTextures.splice(i, 1);
  51882. }
  51883. }
  51884. };
  51885. return MultiRenderTarget;
  51886. }(BABYLON.RenderTargetTexture));
  51887. BABYLON.MultiRenderTarget = MultiRenderTarget;
  51888. })(BABYLON || (BABYLON = {}));
  51889. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  51890. var BABYLON;
  51891. (function (BABYLON) {
  51892. var MirrorTexture = /** @class */ (function (_super) {
  51893. __extends(MirrorTexture, _super);
  51894. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  51895. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  51896. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  51897. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  51898. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  51899. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  51900. _this._transformMatrix = BABYLON.Matrix.Zero();
  51901. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  51902. _this._adaptiveBlurKernel = 0;
  51903. _this._blurKernelX = 0;
  51904. _this._blurKernelY = 0;
  51905. _this._blurRatio = 1.0;
  51906. _this.ignoreCameraViewport = true;
  51907. _this.onBeforeRenderObservable.add(function () {
  51908. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  51909. _this._savedViewMatrix = scene.getViewMatrix();
  51910. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  51911. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  51912. scene.clipPlane = _this.mirrorPlane;
  51913. scene.getEngine().cullBackFaces = false;
  51914. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  51915. });
  51916. _this.onAfterRenderObservable.add(function () {
  51917. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  51918. scene.getEngine().cullBackFaces = true;
  51919. scene._mirroredCameraPosition = null;
  51920. delete scene.clipPlane;
  51921. });
  51922. return _this;
  51923. }
  51924. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  51925. get: function () {
  51926. return this._blurRatio;
  51927. },
  51928. set: function (value) {
  51929. if (this._blurRatio === value) {
  51930. return;
  51931. }
  51932. this._blurRatio = value;
  51933. this._preparePostProcesses();
  51934. },
  51935. enumerable: true,
  51936. configurable: true
  51937. });
  51938. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  51939. set: function (value) {
  51940. this._adaptiveBlurKernel = value;
  51941. this._autoComputeBlurKernel();
  51942. },
  51943. enumerable: true,
  51944. configurable: true
  51945. });
  51946. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  51947. set: function (value) {
  51948. this.blurKernelX = value;
  51949. this.blurKernelY = value;
  51950. },
  51951. enumerable: true,
  51952. configurable: true
  51953. });
  51954. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  51955. get: function () {
  51956. return this._blurKernelX;
  51957. },
  51958. set: function (value) {
  51959. if (this._blurKernelX === value) {
  51960. return;
  51961. }
  51962. this._blurKernelX = value;
  51963. this._preparePostProcesses();
  51964. },
  51965. enumerable: true,
  51966. configurable: true
  51967. });
  51968. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  51969. get: function () {
  51970. return this._blurKernelY;
  51971. },
  51972. set: function (value) {
  51973. if (this._blurKernelY === value) {
  51974. return;
  51975. }
  51976. this._blurKernelY = value;
  51977. this._preparePostProcesses();
  51978. },
  51979. enumerable: true,
  51980. configurable: true
  51981. });
  51982. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  51983. var engine = this.getScene().getEngine();
  51984. var dw = this.getRenderWidth() / engine.getRenderWidth();
  51985. var dh = this.getRenderHeight() / engine.getRenderHeight();
  51986. this.blurKernelX = this._adaptiveBlurKernel * dw;
  51987. this.blurKernelY = this._adaptiveBlurKernel * dh;
  51988. };
  51989. MirrorTexture.prototype._onRatioRescale = function () {
  51990. if (this._sizeRatio) {
  51991. this.resize(this._initialSizeParameter);
  51992. if (!this._adaptiveBlurKernel) {
  51993. this._preparePostProcesses();
  51994. }
  51995. }
  51996. if (this._adaptiveBlurKernel) {
  51997. this._autoComputeBlurKernel();
  51998. }
  51999. };
  52000. MirrorTexture.prototype._preparePostProcesses = function () {
  52001. this.clearPostProcesses(true);
  52002. if (this._blurKernelX && this._blurKernelY) {
  52003. var engine = this.getScene().getEngine();
  52004. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  52005. 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);
  52006. this._blurX.autoClear = false;
  52007. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  52008. this._blurX.outputTexture = this._texture;
  52009. }
  52010. else {
  52011. this._blurX.alwaysForcePOT = true;
  52012. }
  52013. 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);
  52014. this._blurY.autoClear = false;
  52015. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  52016. this.addPostProcess(this._blurX);
  52017. this.addPostProcess(this._blurY);
  52018. }
  52019. else {
  52020. if (this._blurY) {
  52021. this.removePostProcess(this._blurY);
  52022. this._blurY.dispose();
  52023. this._blurY = null;
  52024. }
  52025. if (this._blurX) {
  52026. this.removePostProcess(this._blurX);
  52027. this._blurX.dispose();
  52028. this._blurX = null;
  52029. }
  52030. }
  52031. };
  52032. MirrorTexture.prototype.clone = function () {
  52033. var scene = this.getScene();
  52034. if (!scene) {
  52035. return this;
  52036. }
  52037. var textureSize = this.getSize();
  52038. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  52039. // Base texture
  52040. newTexture.hasAlpha = this.hasAlpha;
  52041. newTexture.level = this.level;
  52042. // Mirror Texture
  52043. newTexture.mirrorPlane = this.mirrorPlane.clone();
  52044. if (this.renderList) {
  52045. newTexture.renderList = this.renderList.slice(0);
  52046. }
  52047. return newTexture;
  52048. };
  52049. MirrorTexture.prototype.serialize = function () {
  52050. if (!this.name) {
  52051. return null;
  52052. }
  52053. var serializationObject = _super.prototype.serialize.call(this);
  52054. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  52055. return serializationObject;
  52056. };
  52057. return MirrorTexture;
  52058. }(BABYLON.RenderTargetTexture));
  52059. BABYLON.MirrorTexture = MirrorTexture;
  52060. })(BABYLON || (BABYLON = {}));
  52061. //# sourceMappingURL=babylon.mirrorTexture.js.map
  52062. var BABYLON;
  52063. (function (BABYLON) {
  52064. /**
  52065. * Creates a refraction texture used by refraction channel of the standard material.
  52066. * @param name the texture name
  52067. * @param size size of the underlying texture
  52068. * @param scene root scene
  52069. */
  52070. var RefractionTexture = /** @class */ (function (_super) {
  52071. __extends(RefractionTexture, _super);
  52072. function RefractionTexture(name, size, scene, generateMipMaps) {
  52073. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  52074. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  52075. _this.depth = 2.0;
  52076. _this.onBeforeRenderObservable.add(function () {
  52077. scene.clipPlane = _this.refractionPlane;
  52078. });
  52079. _this.onAfterRenderObservable.add(function () {
  52080. delete scene.clipPlane;
  52081. });
  52082. return _this;
  52083. }
  52084. RefractionTexture.prototype.clone = function () {
  52085. var scene = this.getScene();
  52086. if (!scene) {
  52087. return this;
  52088. }
  52089. var textureSize = this.getSize();
  52090. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  52091. // Base texture
  52092. newTexture.hasAlpha = this.hasAlpha;
  52093. newTexture.level = this.level;
  52094. // Refraction Texture
  52095. newTexture.refractionPlane = this.refractionPlane.clone();
  52096. if (this.renderList) {
  52097. newTexture.renderList = this.renderList.slice(0);
  52098. }
  52099. newTexture.depth = this.depth;
  52100. return newTexture;
  52101. };
  52102. RefractionTexture.prototype.serialize = function () {
  52103. if (!this.name) {
  52104. return null;
  52105. }
  52106. var serializationObject = _super.prototype.serialize.call(this);
  52107. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  52108. serializationObject.depth = this.depth;
  52109. return serializationObject;
  52110. };
  52111. return RefractionTexture;
  52112. }(BABYLON.RenderTargetTexture));
  52113. BABYLON.RefractionTexture = RefractionTexture;
  52114. })(BABYLON || (BABYLON = {}));
  52115. //# sourceMappingURL=babylon.refractionTexture.js.map
  52116. var BABYLON;
  52117. (function (BABYLON) {
  52118. var DynamicTexture = /** @class */ (function (_super) {
  52119. __extends(DynamicTexture, _super);
  52120. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  52121. if (scene === void 0) { scene = null; }
  52122. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  52123. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  52124. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  52125. _this.name = name;
  52126. _this._engine = _this.getScene().getEngine();
  52127. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52128. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52129. _this._generateMipMaps = generateMipMaps;
  52130. if (options.getContext) {
  52131. _this._canvas = options;
  52132. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  52133. }
  52134. else {
  52135. _this._canvas = document.createElement("canvas");
  52136. if (options.width) {
  52137. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  52138. }
  52139. else {
  52140. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  52141. }
  52142. }
  52143. var textureSize = _this.getSize();
  52144. _this._canvas.width = textureSize.width;
  52145. _this._canvas.height = textureSize.height;
  52146. _this._context = _this._canvas.getContext("2d");
  52147. return _this;
  52148. }
  52149. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  52150. get: function () {
  52151. return true;
  52152. },
  52153. enumerable: true,
  52154. configurable: true
  52155. });
  52156. DynamicTexture.prototype._recreate = function (textureSize) {
  52157. this._canvas.width = textureSize.width;
  52158. this._canvas.height = textureSize.height;
  52159. this.releaseInternalTexture();
  52160. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  52161. };
  52162. DynamicTexture.prototype.scale = function (ratio) {
  52163. var textureSize = this.getSize();
  52164. textureSize.width *= ratio;
  52165. textureSize.height *= ratio;
  52166. this._recreate(textureSize);
  52167. };
  52168. DynamicTexture.prototype.scaleTo = function (width, height) {
  52169. var textureSize = this.getSize();
  52170. textureSize.width = width;
  52171. textureSize.height = height;
  52172. this._recreate(textureSize);
  52173. };
  52174. DynamicTexture.prototype.getContext = function () {
  52175. return this._context;
  52176. };
  52177. DynamicTexture.prototype.clear = function () {
  52178. var size = this.getSize();
  52179. this._context.fillRect(0, 0, size.width, size.height);
  52180. };
  52181. DynamicTexture.prototype.update = function (invertY) {
  52182. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  52183. };
  52184. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  52185. if (update === void 0) { update = true; }
  52186. var size = this.getSize();
  52187. if (clearColor) {
  52188. this._context.fillStyle = clearColor;
  52189. this._context.fillRect(0, 0, size.width, size.height);
  52190. }
  52191. this._context.font = font;
  52192. if (x === null || x === undefined) {
  52193. var textSize = this._context.measureText(text);
  52194. x = (size.width - textSize.width) / 2;
  52195. }
  52196. if (y === null || y === undefined) {
  52197. var fontSize = parseInt((font.replace(/\D/g, '')));
  52198. ;
  52199. y = (size.height / 2) + (fontSize / 3.65);
  52200. }
  52201. this._context.fillStyle = color;
  52202. this._context.fillText(text, x, y);
  52203. if (update) {
  52204. this.update(invertY);
  52205. }
  52206. };
  52207. DynamicTexture.prototype.clone = function () {
  52208. var scene = this.getScene();
  52209. if (!scene) {
  52210. return this;
  52211. }
  52212. var textureSize = this.getSize();
  52213. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  52214. // Base texture
  52215. newTexture.hasAlpha = this.hasAlpha;
  52216. newTexture.level = this.level;
  52217. // Dynamic Texture
  52218. newTexture.wrapU = this.wrapU;
  52219. newTexture.wrapV = this.wrapV;
  52220. return newTexture;
  52221. };
  52222. DynamicTexture.prototype._rebuild = function () {
  52223. this.update();
  52224. };
  52225. return DynamicTexture;
  52226. }(BABYLON.Texture));
  52227. BABYLON.DynamicTexture = DynamicTexture;
  52228. })(BABYLON || (BABYLON = {}));
  52229. //# sourceMappingURL=babylon.dynamicTexture.js.map
  52230. var BABYLON;
  52231. (function (BABYLON) {
  52232. var VideoTexture = /** @class */ (function (_super) {
  52233. __extends(VideoTexture, _super);
  52234. /**
  52235. * Creates a video texture.
  52236. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  52237. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  52238. * @param {BABYLON.Scene} scene is obviously the current scene.
  52239. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  52240. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  52241. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  52242. */
  52243. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  52244. if (generateMipMaps === void 0) { generateMipMaps = false; }
  52245. if (invertY === void 0) { invertY = false; }
  52246. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  52247. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  52248. _this._autoLaunch = true;
  52249. var urls = null;
  52250. _this.name = name;
  52251. if (urlsOrVideo instanceof HTMLVideoElement) {
  52252. _this.video = urlsOrVideo;
  52253. }
  52254. else {
  52255. urls = urlsOrVideo;
  52256. _this.video = document.createElement("video");
  52257. _this.video.autoplay = false;
  52258. _this.video.loop = true;
  52259. BABYLON.Tools.SetCorsBehavior(urls, _this.video);
  52260. }
  52261. _this._engine = _this.getScene().getEngine();
  52262. _this._generateMipMaps = generateMipMaps;
  52263. _this._samplingMode = samplingMode;
  52264. if (!_this._engine.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  52265. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  52266. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  52267. }
  52268. else {
  52269. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52270. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52271. _this._generateMipMaps = false;
  52272. }
  52273. if (urls) {
  52274. _this.video.addEventListener("canplay", function () {
  52275. if (_this._texture === undefined) {
  52276. _this._createTexture();
  52277. }
  52278. });
  52279. urls.forEach(function (url) {
  52280. var source = document.createElement("source");
  52281. source.src = url;
  52282. _this.video.appendChild(source);
  52283. });
  52284. }
  52285. else {
  52286. _this._createTexture();
  52287. }
  52288. _this._lastUpdate = BABYLON.Tools.Now;
  52289. return _this;
  52290. }
  52291. VideoTexture.prototype.__setTextureReady = function () {
  52292. if (this._texture) {
  52293. this._texture.isReady = true;
  52294. }
  52295. };
  52296. VideoTexture.prototype._createTexture = function () {
  52297. this._texture = this._engine.createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode);
  52298. if (this._autoLaunch) {
  52299. this._autoLaunch = false;
  52300. this.video.play();
  52301. }
  52302. this._setTextureReady = this.__setTextureReady.bind(this);
  52303. this.video.addEventListener("playing", this._setTextureReady);
  52304. };
  52305. VideoTexture.prototype._rebuild = function () {
  52306. this.update();
  52307. };
  52308. VideoTexture.prototype.update = function () {
  52309. var now = BABYLON.Tools.Now;
  52310. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  52311. return false;
  52312. }
  52313. this._lastUpdate = now;
  52314. this._engine.updateVideoTexture(this._texture, this.video, this._invertY);
  52315. return true;
  52316. };
  52317. VideoTexture.prototype.dispose = function () {
  52318. _super.prototype.dispose.call(this);
  52319. this.video.removeEventListener("playing", this._setTextureReady);
  52320. };
  52321. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  52322. var video = document.createElement("video");
  52323. var constraintsDeviceId;
  52324. if (constraints && constraints.deviceId) {
  52325. constraintsDeviceId = {
  52326. exact: constraints.deviceId
  52327. };
  52328. }
  52329. navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
  52330. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  52331. if (navigator.getUserMedia) {
  52332. navigator.getUserMedia({
  52333. video: {
  52334. deviceId: constraintsDeviceId,
  52335. width: {
  52336. min: (constraints && constraints.minWidth) || 256,
  52337. max: (constraints && constraints.maxWidth) || 640
  52338. },
  52339. height: {
  52340. min: (constraints && constraints.minHeight) || 256,
  52341. max: (constraints && constraints.maxHeight) || 480
  52342. }
  52343. }
  52344. }, function (stream) {
  52345. if (video.mozSrcObject !== undefined) {
  52346. video.mozSrcObject = stream;
  52347. }
  52348. else {
  52349. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  52350. }
  52351. video.play();
  52352. if (onReady) {
  52353. onReady(new VideoTexture("video", video, scene, true, true));
  52354. }
  52355. }, function (e) {
  52356. BABYLON.Tools.Error(e.name);
  52357. });
  52358. }
  52359. };
  52360. return VideoTexture;
  52361. }(BABYLON.Texture));
  52362. BABYLON.VideoTexture = VideoTexture;
  52363. })(BABYLON || (BABYLON = {}));
  52364. //# sourceMappingURL=babylon.videoTexture.js.map
  52365. var BABYLON;
  52366. (function (BABYLON) {
  52367. var RawTexture = /** @class */ (function (_super) {
  52368. __extends(RawTexture, _super);
  52369. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  52370. if (generateMipMaps === void 0) { generateMipMaps = true; }
  52371. if (invertY === void 0) { invertY = false; }
  52372. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  52373. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  52374. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  52375. _this.format = format;
  52376. _this._engine = scene.getEngine();
  52377. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  52378. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52379. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52380. return _this;
  52381. }
  52382. RawTexture.prototype.update = function (data) {
  52383. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  52384. };
  52385. // Statics
  52386. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  52387. if (generateMipMaps === void 0) { generateMipMaps = true; }
  52388. if (invertY === void 0) { invertY = false; }
  52389. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  52390. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  52391. };
  52392. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  52393. if (generateMipMaps === void 0) { generateMipMaps = true; }
  52394. if (invertY === void 0) { invertY = false; }
  52395. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  52396. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  52397. };
  52398. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  52399. if (generateMipMaps === void 0) { generateMipMaps = true; }
  52400. if (invertY === void 0) { invertY = false; }
  52401. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  52402. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  52403. };
  52404. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  52405. if (generateMipMaps === void 0) { generateMipMaps = true; }
  52406. if (invertY === void 0) { invertY = false; }
  52407. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  52408. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  52409. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  52410. };
  52411. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  52412. if (generateMipMaps === void 0) { generateMipMaps = true; }
  52413. if (invertY === void 0) { invertY = false; }
  52414. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  52415. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  52416. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  52417. };
  52418. return RawTexture;
  52419. }(BABYLON.Texture));
  52420. BABYLON.RawTexture = RawTexture;
  52421. })(BABYLON || (BABYLON = {}));
  52422. //# sourceMappingURL=babylon.rawTexture.js.map
  52423. var BABYLON;
  52424. (function (BABYLON) {
  52425. var PostProcess = /** @class */ (function () {
  52426. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  52427. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  52428. if (defines === void 0) { defines = null; }
  52429. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  52430. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  52431. if (blockCompilation === void 0) { blockCompilation = false; }
  52432. this.name = name;
  52433. this.width = -1;
  52434. this.height = -1;
  52435. this.autoClear = true;
  52436. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  52437. this.animations = new Array();
  52438. /*
  52439. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  52440. Can only be used on a single postprocess or on the last one of a chain.
  52441. */
  52442. this.enablePixelPerfectMode = false;
  52443. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  52444. this.alwaysForcePOT = false;
  52445. this.samples = 1;
  52446. this.adaptScaleToCurrentViewport = false;
  52447. this._reusable = false;
  52448. this._textures = new BABYLON.SmartArray(2);
  52449. this._currentRenderTextureInd = 0;
  52450. this._scaleRatio = new BABYLON.Vector2(1, 1);
  52451. this._texelSize = BABYLON.Vector2.Zero();
  52452. // Events
  52453. /**
  52454. * An event triggered when the postprocess is activated.
  52455. * @type {BABYLON.Observable}
  52456. */
  52457. this.onActivateObservable = new BABYLON.Observable();
  52458. /**
  52459. * An event triggered when the postprocess changes its size.
  52460. * @type {BABYLON.Observable}
  52461. */
  52462. this.onSizeChangedObservable = new BABYLON.Observable();
  52463. /**
  52464. * An event triggered when the postprocess applies its effect.
  52465. * @type {BABYLON.Observable}
  52466. */
  52467. this.onApplyObservable = new BABYLON.Observable();
  52468. /**
  52469. * An event triggered before rendering the postprocess
  52470. * @type {BABYLON.Observable}
  52471. */
  52472. this.onBeforeRenderObservable = new BABYLON.Observable();
  52473. /**
  52474. * An event triggered after rendering the postprocess
  52475. * @type {BABYLON.Observable}
  52476. */
  52477. this.onAfterRenderObservable = new BABYLON.Observable();
  52478. if (camera != null) {
  52479. this._camera = camera;
  52480. this._scene = camera.getScene();
  52481. camera.attachPostProcess(this);
  52482. this._engine = this._scene.getEngine();
  52483. this._scene.postProcesses.push(this);
  52484. }
  52485. else if (engine) {
  52486. this._engine = engine;
  52487. this._engine.postProcesses.push(this);
  52488. }
  52489. this._options = options;
  52490. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  52491. this._reusable = reusable || false;
  52492. this._textureType = textureType;
  52493. this._samplers = samplers || [];
  52494. this._samplers.push("textureSampler");
  52495. this._fragmentUrl = fragmentUrl;
  52496. this._vertexUrl = vertexUrl;
  52497. this._parameters = parameters || [];
  52498. this._parameters.push("scale");
  52499. this._indexParameters = indexParameters;
  52500. if (!blockCompilation) {
  52501. this.updateEffect(defines);
  52502. }
  52503. }
  52504. Object.defineProperty(PostProcess.prototype, "onActivate", {
  52505. set: function (callback) {
  52506. if (this._onActivateObserver) {
  52507. this.onActivateObservable.remove(this._onActivateObserver);
  52508. }
  52509. if (callback) {
  52510. this._onActivateObserver = this.onActivateObservable.add(callback);
  52511. }
  52512. },
  52513. enumerable: true,
  52514. configurable: true
  52515. });
  52516. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  52517. set: function (callback) {
  52518. if (this._onSizeChangedObserver) {
  52519. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  52520. }
  52521. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  52522. },
  52523. enumerable: true,
  52524. configurable: true
  52525. });
  52526. Object.defineProperty(PostProcess.prototype, "onApply", {
  52527. set: function (callback) {
  52528. if (this._onApplyObserver) {
  52529. this.onApplyObservable.remove(this._onApplyObserver);
  52530. }
  52531. this._onApplyObserver = this.onApplyObservable.add(callback);
  52532. },
  52533. enumerable: true,
  52534. configurable: true
  52535. });
  52536. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  52537. set: function (callback) {
  52538. if (this._onBeforeRenderObserver) {
  52539. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  52540. }
  52541. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  52542. },
  52543. enumerable: true,
  52544. configurable: true
  52545. });
  52546. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  52547. set: function (callback) {
  52548. if (this._onAfterRenderObserver) {
  52549. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  52550. }
  52551. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  52552. },
  52553. enumerable: true,
  52554. configurable: true
  52555. });
  52556. Object.defineProperty(PostProcess.prototype, "outputTexture", {
  52557. get: function () {
  52558. return this._textures.data[this._currentRenderTextureInd];
  52559. },
  52560. set: function (value) {
  52561. this._forcedOutputTexture = value;
  52562. },
  52563. enumerable: true,
  52564. configurable: true
  52565. });
  52566. PostProcess.prototype.getCamera = function () {
  52567. return this._camera;
  52568. };
  52569. Object.defineProperty(PostProcess.prototype, "texelSize", {
  52570. get: function () {
  52571. if (this._shareOutputWithPostProcess) {
  52572. return this._shareOutputWithPostProcess.texelSize;
  52573. }
  52574. if (this._forcedOutputTexture) {
  52575. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  52576. }
  52577. return this._texelSize;
  52578. },
  52579. enumerable: true,
  52580. configurable: true
  52581. });
  52582. PostProcess.prototype.getEngine = function () {
  52583. return this._engine;
  52584. };
  52585. PostProcess.prototype.getEffect = function () {
  52586. return this._effect;
  52587. };
  52588. PostProcess.prototype.shareOutputWith = function (postProcess) {
  52589. this._disposeTextures();
  52590. this._shareOutputWithPostProcess = postProcess;
  52591. return this;
  52592. };
  52593. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  52594. if (defines === void 0) { defines = null; }
  52595. if (uniforms === void 0) { uniforms = null; }
  52596. if (samplers === void 0) { samplers = null; }
  52597. 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);
  52598. };
  52599. PostProcess.prototype.isReusable = function () {
  52600. return this._reusable;
  52601. };
  52602. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  52603. PostProcess.prototype.markTextureDirty = function () {
  52604. this.width = -1;
  52605. };
  52606. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  52607. var _this = this;
  52608. if (sourceTexture === void 0) { sourceTexture = null; }
  52609. camera = camera || this._camera;
  52610. var scene = camera.getScene();
  52611. var engine = scene.getEngine();
  52612. var maxSize = engine.getCaps().maxTextureSize;
  52613. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  52614. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  52615. var desiredWidth = (this._options.width || requiredWidth);
  52616. var desiredHeight = this._options.height || requiredHeight;
  52617. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  52618. if (this.adaptScaleToCurrentViewport) {
  52619. var currentViewport = engine.currentViewport;
  52620. if (currentViewport) {
  52621. desiredWidth *= currentViewport.width;
  52622. desiredHeight *= currentViewport.height;
  52623. }
  52624. }
  52625. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  52626. if (!this._options.width) {
  52627. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  52628. }
  52629. if (!this._options.height) {
  52630. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  52631. }
  52632. }
  52633. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  52634. if (this._textures.length > 0) {
  52635. for (var i = 0; i < this._textures.length; i++) {
  52636. this._engine._releaseTexture(this._textures.data[i]);
  52637. }
  52638. this._textures.reset();
  52639. }
  52640. this.width = desiredWidth;
  52641. this.height = desiredHeight;
  52642. var textureSize = { width: this.width, height: this.height };
  52643. var textureOptions = {
  52644. generateMipMaps: false,
  52645. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  52646. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  52647. samplingMode: this.renderTargetSamplingMode,
  52648. type: this._textureType
  52649. };
  52650. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  52651. if (this._reusable) {
  52652. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  52653. }
  52654. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  52655. this.onSizeChangedObservable.notifyObservers(this);
  52656. }
  52657. this._textures.forEach(function (texture) {
  52658. if (texture.samples !== _this.samples) {
  52659. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  52660. }
  52661. });
  52662. }
  52663. var target;
  52664. if (this._shareOutputWithPostProcess) {
  52665. target = this._shareOutputWithPostProcess.outputTexture;
  52666. }
  52667. else if (this._forcedOutputTexture) {
  52668. target = this._forcedOutputTexture;
  52669. this.width = this._forcedOutputTexture.width;
  52670. this.height = this._forcedOutputTexture.height;
  52671. }
  52672. else {
  52673. target = this.outputTexture;
  52674. }
  52675. if (this.enablePixelPerfectMode) {
  52676. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  52677. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  52678. }
  52679. else {
  52680. this._scaleRatio.copyFromFloats(1, 1);
  52681. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  52682. }
  52683. this.onActivateObservable.notifyObservers(camera);
  52684. // Clear
  52685. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  52686. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  52687. }
  52688. if (this._reusable) {
  52689. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  52690. }
  52691. };
  52692. Object.defineProperty(PostProcess.prototype, "isSupported", {
  52693. get: function () {
  52694. return this._effect.isSupported;
  52695. },
  52696. enumerable: true,
  52697. configurable: true
  52698. });
  52699. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  52700. get: function () {
  52701. if (this._shareOutputWithPostProcess) {
  52702. return this._shareOutputWithPostProcess.aspectRatio;
  52703. }
  52704. if (this._forcedOutputTexture) {
  52705. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  52706. }
  52707. return this.width / this.height;
  52708. },
  52709. enumerable: true,
  52710. configurable: true
  52711. });
  52712. PostProcess.prototype.apply = function () {
  52713. // Check
  52714. if (!this._effect || !this._effect.isReady())
  52715. return null;
  52716. // States
  52717. this._engine.enableEffect(this._effect);
  52718. this._engine.setState(false);
  52719. this._engine.setDepthBuffer(false);
  52720. this._engine.setDepthWrite(false);
  52721. // Alpha
  52722. this._engine.setAlphaMode(this.alphaMode);
  52723. if (this.alphaConstants) {
  52724. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  52725. }
  52726. // Texture
  52727. var source;
  52728. if (this._shareOutputWithPostProcess) {
  52729. source = this._shareOutputWithPostProcess.outputTexture;
  52730. }
  52731. else if (this._forcedOutputTexture) {
  52732. source = this._forcedOutputTexture;
  52733. }
  52734. else {
  52735. source = this.outputTexture;
  52736. }
  52737. this._effect._bindTexture("textureSampler", source);
  52738. // Parameters
  52739. this._effect.setVector2("scale", this._scaleRatio);
  52740. this.onApplyObservable.notifyObservers(this._effect);
  52741. return this._effect;
  52742. };
  52743. PostProcess.prototype._disposeTextures = function () {
  52744. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  52745. return;
  52746. }
  52747. if (this._textures.length > 0) {
  52748. for (var i = 0; i < this._textures.length; i++) {
  52749. this._engine._releaseTexture(this._textures.data[i]);
  52750. }
  52751. }
  52752. this._textures.dispose();
  52753. };
  52754. PostProcess.prototype.dispose = function (camera) {
  52755. camera = camera || this._camera;
  52756. this._disposeTextures();
  52757. if (this._scene) {
  52758. var index_1 = this._scene.postProcesses.indexOf(this);
  52759. if (index_1 !== -1) {
  52760. this._scene.postProcesses.splice(index_1, 1);
  52761. }
  52762. }
  52763. else {
  52764. var index_2 = this._engine.postProcesses.indexOf(this);
  52765. if (index_2 !== -1) {
  52766. this._engine.postProcesses.splice(index_2, 1);
  52767. }
  52768. }
  52769. if (!camera) {
  52770. return;
  52771. }
  52772. camera.detachPostProcess(this);
  52773. var index = camera._postProcesses.indexOf(this);
  52774. if (index === 0 && camera._postProcesses.length > 0) {
  52775. this._camera._postProcesses[0].markTextureDirty();
  52776. }
  52777. this.onActivateObservable.clear();
  52778. this.onAfterRenderObservable.clear();
  52779. this.onApplyObservable.clear();
  52780. this.onBeforeRenderObservable.clear();
  52781. this.onSizeChangedObservable.clear();
  52782. };
  52783. return PostProcess;
  52784. }());
  52785. BABYLON.PostProcess = PostProcess;
  52786. })(BABYLON || (BABYLON = {}));
  52787. //# sourceMappingURL=babylon.postProcess.js.map
  52788. var BABYLON;
  52789. (function (BABYLON) {
  52790. var PassPostProcess = /** @class */ (function (_super) {
  52791. __extends(PassPostProcess, _super);
  52792. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  52793. if (camera === void 0) { camera = null; }
  52794. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  52795. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType) || this;
  52796. }
  52797. return PassPostProcess;
  52798. }(BABYLON.PostProcess));
  52799. BABYLON.PassPostProcess = PassPostProcess;
  52800. })(BABYLON || (BABYLON = {}));
  52801. //# sourceMappingURL=babylon.passPostProcess.js.map
  52802. var __assign = (this && this.__assign) || Object.assign || function(t) {
  52803. for (var s, i = 1, n = arguments.length; i < n; i++) {
  52804. s = arguments[i];
  52805. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  52806. t[p] = s[p];
  52807. }
  52808. return t;
  52809. };
  52810. var BABYLON;
  52811. (function (BABYLON) {
  52812. var ShadowGenerator = /** @class */ (function () {
  52813. /**
  52814. * Creates a ShadowGenerator object.
  52815. * A ShadowGenerator is the required tool to use the shadows.
  52816. * Each light casting shadows needs to use its own ShadowGenerator.
  52817. * Required parameters :
  52818. * - `mapSize` (integer): the size of the texture what stores the shadows. Example : 1024.
  52819. * - `light`: the light object generating the shadows.
  52820. * - `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.
  52821. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  52822. */
  52823. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  52824. // Members
  52825. this._bias = 0.00005;
  52826. this._blurBoxOffset = 1;
  52827. this._blurScale = 2;
  52828. this._blurKernel = 1;
  52829. this._useKernelBlur = false;
  52830. this._filter = ShadowGenerator.FILTER_NONE;
  52831. this._darkness = 0;
  52832. this._transparencyShadow = false;
  52833. /**
  52834. * Controls the extent to which the shadows fade out at the edge of the frustum
  52835. * Used only by directionals and spots
  52836. */
  52837. this.frustumEdgeFalloff = 0;
  52838. this.forceBackFacesOnly = false;
  52839. this._lightDirection = BABYLON.Vector3.Zero();
  52840. this._viewMatrix = BABYLON.Matrix.Zero();
  52841. this._projectionMatrix = BABYLON.Matrix.Zero();
  52842. this._transformMatrix = BABYLON.Matrix.Zero();
  52843. this._currentFaceIndex = 0;
  52844. this._currentFaceIndexCache = 0;
  52845. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  52846. this._mapSize = mapSize;
  52847. this._light = light;
  52848. this._scene = light.getScene();
  52849. light._shadowGenerator = this;
  52850. // Texture type fallback from float to int if not supported.
  52851. var caps = this._scene.getEngine().getCaps();
  52852. if (!useFullFloatFirst) {
  52853. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  52854. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  52855. }
  52856. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  52857. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  52858. }
  52859. else {
  52860. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  52861. }
  52862. }
  52863. else {
  52864. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  52865. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  52866. }
  52867. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  52868. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  52869. }
  52870. else {
  52871. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  52872. }
  52873. }
  52874. this._initializeGenerator();
  52875. }
  52876. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  52877. // Static
  52878. get: function () {
  52879. return ShadowGenerator._FILTER_NONE;
  52880. },
  52881. enumerable: true,
  52882. configurable: true
  52883. });
  52884. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  52885. get: function () {
  52886. return ShadowGenerator._FILTER_POISSONSAMPLING;
  52887. },
  52888. enumerable: true,
  52889. configurable: true
  52890. });
  52891. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  52892. get: function () {
  52893. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  52894. },
  52895. enumerable: true,
  52896. configurable: true
  52897. });
  52898. Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", {
  52899. get: function () {
  52900. return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP;
  52901. },
  52902. enumerable: true,
  52903. configurable: true
  52904. });
  52905. Object.defineProperty(ShadowGenerator, "FILTER_CLOSEEXPONENTIALSHADOWMAP", {
  52906. get: function () {
  52907. return ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP;
  52908. },
  52909. enumerable: true,
  52910. configurable: true
  52911. });
  52912. Object.defineProperty(ShadowGenerator, "FILTER_BLURCLOSEEXPONENTIALSHADOWMAP", {
  52913. get: function () {
  52914. return ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  52915. },
  52916. enumerable: true,
  52917. configurable: true
  52918. });
  52919. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  52920. get: function () {
  52921. return this._bias;
  52922. },
  52923. set: function (bias) {
  52924. this._bias = bias;
  52925. },
  52926. enumerable: true,
  52927. configurable: true
  52928. });
  52929. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  52930. get: function () {
  52931. return this._blurBoxOffset;
  52932. },
  52933. set: function (value) {
  52934. if (this._blurBoxOffset === value) {
  52935. return;
  52936. }
  52937. this._blurBoxOffset = value;
  52938. this._disposeBlurPostProcesses();
  52939. },
  52940. enumerable: true,
  52941. configurable: true
  52942. });
  52943. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  52944. get: function () {
  52945. return this._blurScale;
  52946. },
  52947. set: function (value) {
  52948. if (this._blurScale === value) {
  52949. return;
  52950. }
  52951. this._blurScale = value;
  52952. this._disposeBlurPostProcesses();
  52953. },
  52954. enumerable: true,
  52955. configurable: true
  52956. });
  52957. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  52958. get: function () {
  52959. return this._blurKernel;
  52960. },
  52961. set: function (value) {
  52962. if (this._blurKernel === value) {
  52963. return;
  52964. }
  52965. this._blurKernel = value;
  52966. this._disposeBlurPostProcesses();
  52967. },
  52968. enumerable: true,
  52969. configurable: true
  52970. });
  52971. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  52972. get: function () {
  52973. return this._useKernelBlur;
  52974. },
  52975. set: function (value) {
  52976. if (this._useKernelBlur === value) {
  52977. return;
  52978. }
  52979. this._useKernelBlur = value;
  52980. this._disposeBlurPostProcesses();
  52981. },
  52982. enumerable: true,
  52983. configurable: true
  52984. });
  52985. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  52986. get: function () {
  52987. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  52988. },
  52989. set: function (value) {
  52990. this._depthScale = value;
  52991. },
  52992. enumerable: true,
  52993. configurable: true
  52994. });
  52995. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  52996. get: function () {
  52997. return this._filter;
  52998. },
  52999. set: function (value) {
  53000. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  53001. if (this._light.needCube()) {
  53002. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  53003. this.useExponentialShadowMap = true;
  53004. return;
  53005. }
  53006. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  53007. this.useCloseExponentialShadowMap = true;
  53008. return;
  53009. }
  53010. }
  53011. if (this._filter === value) {
  53012. return;
  53013. }
  53014. this._filter = value;
  53015. this._disposeBlurPostProcesses();
  53016. this._applyFilterValues();
  53017. this._light._markMeshesAsLightDirty();
  53018. },
  53019. enumerable: true,
  53020. configurable: true
  53021. });
  53022. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  53023. get: function () {
  53024. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  53025. },
  53026. set: function (value) {
  53027. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  53028. return;
  53029. }
  53030. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  53031. },
  53032. enumerable: true,
  53033. configurable: true
  53034. });
  53035. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  53036. get: function () {
  53037. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  53038. return this.useExponentialShadowMap;
  53039. },
  53040. set: function (value) {
  53041. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  53042. this.useExponentialShadowMap = value;
  53043. },
  53044. enumerable: true,
  53045. configurable: true
  53046. });
  53047. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  53048. get: function () {
  53049. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  53050. return this.useBlurExponentialShadowMap;
  53051. },
  53052. set: function (value) {
  53053. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  53054. this.useBlurExponentialShadowMap = value;
  53055. },
  53056. enumerable: true,
  53057. configurable: true
  53058. });
  53059. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  53060. get: function () {
  53061. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  53062. },
  53063. set: function (value) {
  53064. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  53065. return;
  53066. }
  53067. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  53068. },
  53069. enumerable: true,
  53070. configurable: true
  53071. });
  53072. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  53073. get: function () {
  53074. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  53075. },
  53076. set: function (value) {
  53077. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  53078. return;
  53079. }
  53080. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  53081. },
  53082. enumerable: true,
  53083. configurable: true
  53084. });
  53085. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  53086. get: function () {
  53087. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  53088. },
  53089. set: function (value) {
  53090. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  53091. return;
  53092. }
  53093. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  53094. },
  53095. enumerable: true,
  53096. configurable: true
  53097. });
  53098. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  53099. get: function () {
  53100. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  53101. },
  53102. set: function (value) {
  53103. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  53104. return;
  53105. }
  53106. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  53107. },
  53108. enumerable: true,
  53109. configurable: true
  53110. });
  53111. /**
  53112. * Returns the darkness value (float).
  53113. */
  53114. ShadowGenerator.prototype.getDarkness = function () {
  53115. return this._darkness;
  53116. };
  53117. /**
  53118. * Sets the ShadowGenerator darkness value (float <= 1.0).
  53119. * Returns the ShadowGenerator.
  53120. */
  53121. ShadowGenerator.prototype.setDarkness = function (darkness) {
  53122. if (darkness >= 1.0)
  53123. this._darkness = 1.0;
  53124. else if (darkness <= 0.0)
  53125. this._darkness = 0.0;
  53126. else
  53127. this._darkness = darkness;
  53128. return this;
  53129. };
  53130. /**
  53131. * Sets the ability to have transparent shadow (boolean).
  53132. * Returns the ShadowGenerator.
  53133. */
  53134. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  53135. this._transparencyShadow = hasShadow;
  53136. return this;
  53137. };
  53138. /**
  53139. * Returns a RenderTargetTexture object : the shadow map texture.
  53140. */
  53141. ShadowGenerator.prototype.getShadowMap = function () {
  53142. return this._shadowMap;
  53143. };
  53144. /**
  53145. * Returns the most ready computed shadow map as a RenderTargetTexture object.
  53146. */
  53147. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  53148. if (this._shadowMap2) {
  53149. return this._shadowMap2;
  53150. }
  53151. return this._shadowMap;
  53152. };
  53153. /**
  53154. * Helper function to add a mesh and its descendants to the list of shadow casters
  53155. * @param mesh Mesh to add
  53156. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  53157. */
  53158. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  53159. if (includeDescendants === void 0) { includeDescendants = true; }
  53160. if (!this._shadowMap) {
  53161. return this;
  53162. }
  53163. if (!this._shadowMap.renderList) {
  53164. this._shadowMap.renderList = [];
  53165. }
  53166. this._shadowMap.renderList.push(mesh);
  53167. if (includeDescendants) {
  53168. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  53169. }
  53170. return this;
  53171. var _a;
  53172. };
  53173. /**
  53174. * Helper function to remove a mesh and its descendants from the list of shadow casters
  53175. * @param mesh Mesh to remove
  53176. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  53177. */
  53178. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  53179. if (includeDescendants === void 0) { includeDescendants = true; }
  53180. if (!this._shadowMap || !this._shadowMap.renderList) {
  53181. return this;
  53182. }
  53183. var index = this._shadowMap.renderList.indexOf(mesh);
  53184. if (index !== -1) {
  53185. this._shadowMap.renderList.splice(index, 1);
  53186. }
  53187. if (includeDescendants) {
  53188. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  53189. var child = _a[_i];
  53190. this.removeShadowCaster(child);
  53191. }
  53192. }
  53193. return this;
  53194. };
  53195. /**
  53196. * Returns the associated light object.
  53197. */
  53198. ShadowGenerator.prototype.getLight = function () {
  53199. return this._light;
  53200. };
  53201. ShadowGenerator.prototype._initializeGenerator = function () {
  53202. this._light._markMeshesAsLightDirty();
  53203. this._initializeShadowMap();
  53204. };
  53205. ShadowGenerator.prototype._initializeShadowMap = function () {
  53206. var _this = this;
  53207. // Render target
  53208. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  53209. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53210. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53211. this._shadowMap.anisotropicFilteringLevel = 1;
  53212. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  53213. this._shadowMap.renderParticles = false;
  53214. this._shadowMap.ignoreCameraViewport = true;
  53215. // Record Face Index before render.
  53216. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  53217. _this._currentFaceIndex = faceIndex;
  53218. });
  53219. // Custom render function.
  53220. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  53221. // Blur if required afer render.
  53222. this._shadowMap.onAfterUnbindObservable.add(function () {
  53223. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  53224. return;
  53225. }
  53226. if (!_this._blurPostProcesses || !_this._blurPostProcesses.length) {
  53227. _this._initializeBlurRTTAndPostProcesses();
  53228. }
  53229. var shadowMap = _this.getShadowMapForRendering();
  53230. if (shadowMap) {
  53231. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  53232. }
  53233. });
  53234. // Clear according to the chosen filter.
  53235. this._shadowMap.onClearObservable.add(function (engine) {
  53236. if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  53237. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  53238. }
  53239. else {
  53240. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  53241. }
  53242. });
  53243. };
  53244. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  53245. var _this = this;
  53246. var engine = this._scene.getEngine();
  53247. var targetSize = this._mapSize / this.blurScale;
  53248. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  53249. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  53250. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53251. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53252. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  53253. }
  53254. if (this.useKernelBlur) {
  53255. 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);
  53256. this._kernelBlurXPostprocess.width = targetSize;
  53257. this._kernelBlurXPostprocess.height = targetSize;
  53258. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  53259. effect.setTexture("textureSampler", _this._shadowMap);
  53260. });
  53261. 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);
  53262. this._kernelBlurXPostprocess.autoClear = false;
  53263. this._kernelBlurYPostprocess.autoClear = false;
  53264. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  53265. this._kernelBlurXPostprocess.packedFloat = true;
  53266. this._kernelBlurYPostprocess.packedFloat = true;
  53267. }
  53268. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  53269. }
  53270. else {
  53271. 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);
  53272. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  53273. effect.setFloat2("screenSize", targetSize, targetSize);
  53274. effect.setTexture("textureSampler", _this._shadowMap);
  53275. });
  53276. this._boxBlurPostprocess.autoClear = false;
  53277. this._blurPostProcesses = [this._boxBlurPostprocess];
  53278. }
  53279. };
  53280. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  53281. var index;
  53282. var engine = this._scene.getEngine();
  53283. if (depthOnlySubMeshes.length) {
  53284. engine.setColorWrite(false);
  53285. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  53286. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  53287. }
  53288. engine.setColorWrite(true);
  53289. }
  53290. for (index = 0; index < opaqueSubMeshes.length; index++) {
  53291. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  53292. }
  53293. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  53294. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  53295. }
  53296. if (this._transparencyShadow) {
  53297. for (index = 0; index < transparentSubMeshes.length; index++) {
  53298. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  53299. }
  53300. }
  53301. };
  53302. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  53303. var _this = this;
  53304. var mesh = subMesh.getRenderingMesh();
  53305. var scene = this._scene;
  53306. var engine = scene.getEngine();
  53307. var material = subMesh.getMaterial();
  53308. if (!material) {
  53309. return;
  53310. }
  53311. // Culling
  53312. engine.setState(material.backFaceCulling);
  53313. // Managing instances
  53314. var batch = mesh._getInstancesRenderList(subMesh._id);
  53315. if (batch.mustReturn) {
  53316. return;
  53317. }
  53318. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  53319. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  53320. engine.enableEffect(this._effect);
  53321. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  53322. this._effect.setFloat2("biasAndScale", this.bias, this.depthScale);
  53323. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  53324. this._effect.setVector3("lightPosition", this.getLight().position);
  53325. if (scene.activeCamera) {
  53326. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  53327. }
  53328. // Alpha test
  53329. if (material && material.needAlphaTesting()) {
  53330. var alphaTexture = material.getAlphaTestTexture();
  53331. if (alphaTexture) {
  53332. this._effect.setTexture("diffuseSampler", alphaTexture);
  53333. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  53334. }
  53335. }
  53336. // Bones
  53337. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  53338. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  53339. }
  53340. if (this.forceBackFacesOnly) {
  53341. engine.setState(true, 0, false, true);
  53342. }
  53343. // Draw
  53344. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  53345. if (this.forceBackFacesOnly) {
  53346. engine.setState(true, 0, false, false);
  53347. }
  53348. }
  53349. else {
  53350. // Need to reset refresh rate of the shadowMap
  53351. if (this._shadowMap) {
  53352. this._shadowMap.resetRefreshCounter();
  53353. }
  53354. }
  53355. };
  53356. ShadowGenerator.prototype._applyFilterValues = function () {
  53357. if (!this._shadowMap) {
  53358. return;
  53359. }
  53360. if (this.filter === ShadowGenerator.FILTER_NONE) {
  53361. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  53362. }
  53363. else {
  53364. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  53365. }
  53366. };
  53367. /**
  53368. * Force shader compilation including textures ready check
  53369. */
  53370. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  53371. var _this = this;
  53372. var localOptions = __assign({ useInstances: false }, options);
  53373. var shadowMap = this.getShadowMap();
  53374. if (!shadowMap) {
  53375. if (onCompiled) {
  53376. onCompiled(this);
  53377. }
  53378. return;
  53379. }
  53380. var renderList = shadowMap.renderList;
  53381. if (!renderList) {
  53382. if (onCompiled) {
  53383. onCompiled(this);
  53384. }
  53385. return;
  53386. }
  53387. var subMeshes = new Array();
  53388. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  53389. var mesh = renderList_1[_i];
  53390. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  53391. }
  53392. if (subMeshes.length === 0) {
  53393. if (onCompiled) {
  53394. onCompiled(this);
  53395. }
  53396. return;
  53397. }
  53398. var currentIndex = 0;
  53399. var checkReady = function () {
  53400. if (!_this._scene || !_this._scene.getEngine()) {
  53401. return;
  53402. }
  53403. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  53404. currentIndex++;
  53405. if (currentIndex >= subMeshes.length) {
  53406. if (onCompiled) {
  53407. onCompiled(_this);
  53408. }
  53409. return;
  53410. }
  53411. }
  53412. setTimeout(checkReady, 16);
  53413. };
  53414. checkReady();
  53415. };
  53416. /**
  53417. * Boolean : true when the ShadowGenerator is finally computed.
  53418. */
  53419. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  53420. var defines = [];
  53421. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  53422. defines.push("#define FLOAT");
  53423. }
  53424. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  53425. defines.push("#define ESM");
  53426. }
  53427. var attribs = [BABYLON.VertexBuffer.PositionKind];
  53428. var mesh = subMesh.getMesh();
  53429. var material = subMesh.getMaterial();
  53430. // Alpha test
  53431. if (material && material.needAlphaTesting()) {
  53432. var alphaTexture = material.getAlphaTestTexture();
  53433. if (alphaTexture) {
  53434. defines.push("#define ALPHATEST");
  53435. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  53436. attribs.push(BABYLON.VertexBuffer.UVKind);
  53437. defines.push("#define UV1");
  53438. }
  53439. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  53440. if (alphaTexture.coordinatesIndex === 1) {
  53441. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  53442. defines.push("#define UV2");
  53443. }
  53444. }
  53445. }
  53446. }
  53447. // Bones
  53448. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  53449. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  53450. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  53451. if (mesh.numBoneInfluencers > 4) {
  53452. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  53453. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  53454. }
  53455. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  53456. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  53457. }
  53458. else {
  53459. defines.push("#define NUM_BONE_INFLUENCERS 0");
  53460. }
  53461. // Instances
  53462. if (useInstances) {
  53463. defines.push("#define INSTANCES");
  53464. attribs.push("world0");
  53465. attribs.push("world1");
  53466. attribs.push("world2");
  53467. attribs.push("world3");
  53468. }
  53469. // Get correct effect
  53470. var join = defines.join("\n");
  53471. if (this._cachedDefines !== join) {
  53472. this._cachedDefines = join;
  53473. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  53474. }
  53475. return this._effect.isReady();
  53476. };
  53477. /**
  53478. * This creates the defines related to the standard BJS materials.
  53479. */
  53480. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  53481. var scene = this._scene;
  53482. var light = this._light;
  53483. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  53484. return;
  53485. }
  53486. defines["SHADOW" + lightIndex] = true;
  53487. if (this.usePoissonSampling) {
  53488. defines["SHADOWPCF" + lightIndex] = true;
  53489. }
  53490. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  53491. defines["SHADOWESM" + lightIndex] = true;
  53492. }
  53493. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  53494. defines["SHADOWCLOSEESM" + lightIndex] = true;
  53495. }
  53496. if (light.needCube()) {
  53497. defines["SHADOWCUBE" + lightIndex] = true;
  53498. }
  53499. };
  53500. /**
  53501. * This binds shadow lights related to the standard BJS materials.
  53502. * It implies the unifroms available on the materials are the standard BJS ones.
  53503. */
  53504. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  53505. var light = this._light;
  53506. var scene = this._scene;
  53507. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  53508. return;
  53509. }
  53510. var camera = scene.activeCamera;
  53511. if (!camera) {
  53512. return;
  53513. }
  53514. var shadowMap = this.getShadowMap();
  53515. if (!shadowMap) {
  53516. return;
  53517. }
  53518. if (!light.needCube()) {
  53519. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  53520. }
  53521. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  53522. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  53523. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  53524. };
  53525. // Methods
  53526. /**
  53527. * Returns a Matrix object : the updated transformation matrix.
  53528. */
  53529. ShadowGenerator.prototype.getTransformMatrix = function () {
  53530. var scene = this._scene;
  53531. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  53532. return this._transformMatrix;
  53533. }
  53534. this._currentRenderID = scene.getRenderId();
  53535. this._currentFaceIndexCache = this._currentFaceIndex;
  53536. var lightPosition = this._light.position;
  53537. if (this._light.computeTransformedInformation()) {
  53538. lightPosition = this._light.transformedPosition;
  53539. }
  53540. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  53541. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  53542. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  53543. }
  53544. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  53545. this._cachedPosition = lightPosition.clone();
  53546. this._cachedDirection = this._lightDirection.clone();
  53547. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  53548. var shadowMap = this.getShadowMap();
  53549. if (shadowMap) {
  53550. var renderList = shadowMap.renderList;
  53551. if (renderList) {
  53552. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  53553. }
  53554. }
  53555. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  53556. }
  53557. return this._transformMatrix;
  53558. };
  53559. ShadowGenerator.prototype.recreateShadowMap = function () {
  53560. var shadowMap = this._shadowMap;
  53561. if (!shadowMap) {
  53562. return;
  53563. }
  53564. // Track render list.
  53565. var renderList = shadowMap.renderList;
  53566. // Clean up existing data.
  53567. this._disposeRTTandPostProcesses();
  53568. // Reinitializes.
  53569. this._initializeGenerator();
  53570. // Reaffect the filter to ensure a correct fallback if necessary.
  53571. this.filter = this.filter;
  53572. // Reaffect the filter.
  53573. this._applyFilterValues();
  53574. // Reaffect Render List.
  53575. this._shadowMap.renderList = renderList;
  53576. };
  53577. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  53578. if (this._shadowMap2) {
  53579. this._shadowMap2.dispose();
  53580. this._shadowMap2 = null;
  53581. }
  53582. if (this._downSamplePostprocess) {
  53583. this._downSamplePostprocess.dispose();
  53584. this._downSamplePostprocess = null;
  53585. }
  53586. if (this._boxBlurPostprocess) {
  53587. this._boxBlurPostprocess.dispose();
  53588. this._boxBlurPostprocess = null;
  53589. }
  53590. if (this._kernelBlurXPostprocess) {
  53591. this._kernelBlurXPostprocess.dispose();
  53592. this._kernelBlurXPostprocess = null;
  53593. }
  53594. if (this._kernelBlurYPostprocess) {
  53595. this._kernelBlurYPostprocess.dispose();
  53596. this._kernelBlurYPostprocess = null;
  53597. }
  53598. this._blurPostProcesses = [];
  53599. };
  53600. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  53601. if (this._shadowMap) {
  53602. this._shadowMap.dispose();
  53603. this._shadowMap = null;
  53604. }
  53605. this._disposeBlurPostProcesses();
  53606. };
  53607. /**
  53608. * Disposes the ShadowGenerator.
  53609. * Returns nothing.
  53610. */
  53611. ShadowGenerator.prototype.dispose = function () {
  53612. this._disposeRTTandPostProcesses();
  53613. if (this._light) {
  53614. this._light._shadowGenerator = null;
  53615. this._light._markMeshesAsLightDirty();
  53616. }
  53617. };
  53618. /**
  53619. * Serializes the ShadowGenerator and returns a serializationObject.
  53620. */
  53621. ShadowGenerator.prototype.serialize = function () {
  53622. var serializationObject = {};
  53623. var shadowMap = this.getShadowMap();
  53624. if (!shadowMap) {
  53625. return serializationObject;
  53626. }
  53627. serializationObject.lightId = this._light.id;
  53628. serializationObject.mapSize = shadowMap.getRenderSize();
  53629. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  53630. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  53631. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  53632. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  53633. serializationObject.usePoissonSampling = this.usePoissonSampling;
  53634. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  53635. serializationObject.depthScale = this.depthScale;
  53636. serializationObject.darkness = this.getDarkness();
  53637. serializationObject.blurBoxOffset = this.blurBoxOffset;
  53638. serializationObject.blurKernel = this.blurKernel;
  53639. serializationObject.blurScale = this.blurScale;
  53640. serializationObject.useKernelBlur = this.useKernelBlur;
  53641. serializationObject.transparencyShadow = this._transparencyShadow;
  53642. serializationObject.renderList = [];
  53643. if (shadowMap.renderList) {
  53644. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  53645. var mesh = shadowMap.renderList[meshIndex];
  53646. serializationObject.renderList.push(mesh.id);
  53647. }
  53648. }
  53649. return serializationObject;
  53650. };
  53651. /**
  53652. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  53653. */
  53654. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  53655. //casting to point light, as light is missing the position attr and typescript complains.
  53656. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  53657. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  53658. var shadowMap = shadowGenerator.getShadowMap();
  53659. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  53660. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  53661. meshes.forEach(function (mesh) {
  53662. if (!shadowMap) {
  53663. return;
  53664. }
  53665. if (!shadowMap.renderList) {
  53666. shadowMap.renderList = [];
  53667. }
  53668. shadowMap.renderList.push(mesh);
  53669. });
  53670. }
  53671. if (parsedShadowGenerator.usePoissonSampling) {
  53672. shadowGenerator.usePoissonSampling = true;
  53673. }
  53674. else if (parsedShadowGenerator.useExponentialShadowMap) {
  53675. shadowGenerator.useExponentialShadowMap = true;
  53676. }
  53677. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  53678. shadowGenerator.useBlurExponentialShadowMap = true;
  53679. }
  53680. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  53681. shadowGenerator.useCloseExponentialShadowMap = true;
  53682. }
  53683. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  53684. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  53685. }
  53686. else if (parsedShadowGenerator.useVarianceShadowMap) {
  53687. shadowGenerator.useExponentialShadowMap = true;
  53688. }
  53689. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  53690. shadowGenerator.useBlurExponentialShadowMap = true;
  53691. }
  53692. if (parsedShadowGenerator.depthScale) {
  53693. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  53694. }
  53695. if (parsedShadowGenerator.blurScale) {
  53696. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  53697. }
  53698. if (parsedShadowGenerator.blurBoxOffset) {
  53699. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  53700. }
  53701. if (parsedShadowGenerator.useKernelBlur) {
  53702. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  53703. }
  53704. if (parsedShadowGenerator.blurKernel) {
  53705. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  53706. }
  53707. if (parsedShadowGenerator.bias !== undefined) {
  53708. shadowGenerator.bias = parsedShadowGenerator.bias;
  53709. }
  53710. if (parsedShadowGenerator.darkness) {
  53711. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  53712. }
  53713. if (parsedShadowGenerator.transparencyShadow) {
  53714. shadowGenerator.setTransparencyShadow(true);
  53715. }
  53716. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  53717. return shadowGenerator;
  53718. };
  53719. ShadowGenerator._FILTER_NONE = 0;
  53720. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1;
  53721. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  53722. ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  53723. ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  53724. ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  53725. return ShadowGenerator;
  53726. }());
  53727. BABYLON.ShadowGenerator = ShadowGenerator;
  53728. })(BABYLON || (BABYLON = {}));
  53729. //# sourceMappingURL=babylon.shadowGenerator.js.map
  53730. var BABYLON;
  53731. (function (BABYLON) {
  53732. var DefaultLoadingScreen = /** @class */ (function () {
  53733. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  53734. if (_loadingText === void 0) { _loadingText = ""; }
  53735. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  53736. var _this = this;
  53737. this._renderingCanvas = _renderingCanvas;
  53738. this._loadingText = _loadingText;
  53739. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  53740. // Resize
  53741. this._resizeLoadingUI = function () {
  53742. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  53743. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  53744. if (!_this._loadingDiv) {
  53745. return;
  53746. }
  53747. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  53748. _this._loadingDiv.style.left = canvasRect.left + "px";
  53749. _this._loadingDiv.style.top = canvasRect.top + "px";
  53750. _this._loadingDiv.style.width = canvasRect.width + "px";
  53751. _this._loadingDiv.style.height = canvasRect.height + "px";
  53752. };
  53753. }
  53754. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  53755. if (this._loadingDiv) {
  53756. // Do not add a loading screen if there is already one
  53757. return;
  53758. }
  53759. this._loadingDiv = document.createElement("div");
  53760. this._loadingDiv.id = "babylonjsLoadingDiv";
  53761. this._loadingDiv.style.opacity = "0";
  53762. this._loadingDiv.style.transition = "opacity 1.5s ease";
  53763. this._loadingDiv.style.pointerEvents = "none";
  53764. // Loading text
  53765. this._loadingTextDiv = document.createElement("div");
  53766. this._loadingTextDiv.style.position = "absolute";
  53767. this._loadingTextDiv.style.left = "0";
  53768. this._loadingTextDiv.style.top = "50%";
  53769. this._loadingTextDiv.style.marginTop = "80px";
  53770. this._loadingTextDiv.style.width = "100%";
  53771. this._loadingTextDiv.style.height = "20px";
  53772. this._loadingTextDiv.style.fontFamily = "Arial";
  53773. this._loadingTextDiv.style.fontSize = "14px";
  53774. this._loadingTextDiv.style.color = "white";
  53775. this._loadingTextDiv.style.textAlign = "center";
  53776. this._loadingTextDiv.innerHTML = "Loading";
  53777. this._loadingDiv.appendChild(this._loadingTextDiv);
  53778. //set the predefined text
  53779. this._loadingTextDiv.innerHTML = this._loadingText;
  53780. // Generating keyframes
  53781. var style = document.createElement('style');
  53782. style.type = 'text/css';
  53783. 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 }";
  53784. style.innerHTML = keyFrames;
  53785. document.getElementsByTagName('head')[0].appendChild(style);
  53786. // Loading img
  53787. var imgBack = new Image();
  53788. 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";
  53789. imgBack.style.position = "absolute";
  53790. imgBack.style.left = "50%";
  53791. imgBack.style.top = "50%";
  53792. imgBack.style.marginLeft = "-60px";
  53793. imgBack.style.marginTop = "-60px";
  53794. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  53795. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  53796. imgBack.style.transformOrigin = "50% 50%";
  53797. imgBack.style.webkitTransformOrigin = "50% 50%";
  53798. this._loadingDiv.appendChild(imgBack);
  53799. this._resizeLoadingUI();
  53800. window.addEventListener("resize", this._resizeLoadingUI);
  53801. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  53802. document.body.appendChild(this._loadingDiv);
  53803. this._loadingDiv.style.opacity = "1";
  53804. };
  53805. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  53806. var _this = this;
  53807. if (!this._loadingDiv) {
  53808. return;
  53809. }
  53810. var onTransitionEnd = function () {
  53811. if (!_this._loadingDiv) {
  53812. return;
  53813. }
  53814. document.body.removeChild(_this._loadingDiv);
  53815. window.removeEventListener("resize", _this._resizeLoadingUI);
  53816. _this._loadingDiv = null;
  53817. };
  53818. this._loadingDiv.style.opacity = "0";
  53819. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  53820. };
  53821. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  53822. set: function (text) {
  53823. this._loadingText = text;
  53824. if (this._loadingTextDiv) {
  53825. this._loadingTextDiv.innerHTML = this._loadingText;
  53826. }
  53827. },
  53828. enumerable: true,
  53829. configurable: true
  53830. });
  53831. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  53832. get: function () {
  53833. return this._loadingDivBackgroundColor;
  53834. },
  53835. set: function (color) {
  53836. this._loadingDivBackgroundColor = color;
  53837. if (!this._loadingDiv) {
  53838. return;
  53839. }
  53840. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  53841. },
  53842. enumerable: true,
  53843. configurable: true
  53844. });
  53845. return DefaultLoadingScreen;
  53846. }());
  53847. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  53848. })(BABYLON || (BABYLON = {}));
  53849. //# sourceMappingURL=babylon.loadingScreen.js.map
  53850. var BABYLON;
  53851. (function (BABYLON) {
  53852. var SceneLoaderProgressEvent = /** @class */ (function () {
  53853. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  53854. this.lengthComputable = lengthComputable;
  53855. this.loaded = loaded;
  53856. this.total = total;
  53857. }
  53858. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  53859. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  53860. };
  53861. return SceneLoaderProgressEvent;
  53862. }());
  53863. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  53864. var SceneLoader = /** @class */ (function () {
  53865. function SceneLoader() {
  53866. }
  53867. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  53868. get: function () {
  53869. return 0;
  53870. },
  53871. enumerable: true,
  53872. configurable: true
  53873. });
  53874. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  53875. get: function () {
  53876. return 1;
  53877. },
  53878. enumerable: true,
  53879. configurable: true
  53880. });
  53881. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  53882. get: function () {
  53883. return 2;
  53884. },
  53885. enumerable: true,
  53886. configurable: true
  53887. });
  53888. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  53889. get: function () {
  53890. return 3;
  53891. },
  53892. enumerable: true,
  53893. configurable: true
  53894. });
  53895. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  53896. get: function () {
  53897. return SceneLoader._ForceFullSceneLoadingForIncremental;
  53898. },
  53899. set: function (value) {
  53900. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  53901. },
  53902. enumerable: true,
  53903. configurable: true
  53904. });
  53905. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  53906. get: function () {
  53907. return SceneLoader._ShowLoadingScreen;
  53908. },
  53909. set: function (value) {
  53910. SceneLoader._ShowLoadingScreen = value;
  53911. },
  53912. enumerable: true,
  53913. configurable: true
  53914. });
  53915. Object.defineProperty(SceneLoader, "loggingLevel", {
  53916. get: function () {
  53917. return SceneLoader._loggingLevel;
  53918. },
  53919. set: function (value) {
  53920. SceneLoader._loggingLevel = value;
  53921. },
  53922. enumerable: true,
  53923. configurable: true
  53924. });
  53925. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  53926. get: function () {
  53927. return SceneLoader._CleanBoneMatrixWeights;
  53928. },
  53929. set: function (value) {
  53930. SceneLoader._CleanBoneMatrixWeights = value;
  53931. },
  53932. enumerable: true,
  53933. configurable: true
  53934. });
  53935. SceneLoader._getDefaultPlugin = function () {
  53936. return SceneLoader._registeredPlugins[".babylon"];
  53937. };
  53938. SceneLoader._getPluginForExtension = function (extension) {
  53939. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  53940. if (registeredPlugin) {
  53941. return registeredPlugin;
  53942. }
  53943. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin.");
  53944. return SceneLoader._getDefaultPlugin();
  53945. };
  53946. SceneLoader._getPluginForDirectLoad = function (data) {
  53947. for (var extension in SceneLoader._registeredPlugins) {
  53948. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  53949. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  53950. return SceneLoader._registeredPlugins[extension];
  53951. }
  53952. }
  53953. return SceneLoader._getDefaultPlugin();
  53954. };
  53955. SceneLoader._getPluginForFilename = function (sceneFilename) {
  53956. if (sceneFilename.name) {
  53957. sceneFilename = sceneFilename.name;
  53958. }
  53959. var queryStringPosition = sceneFilename.indexOf("?");
  53960. if (queryStringPosition !== -1) {
  53961. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  53962. }
  53963. var dotPosition = sceneFilename.lastIndexOf(".");
  53964. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  53965. return SceneLoader._getPluginForExtension(extension);
  53966. };
  53967. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  53968. SceneLoader._getDirectLoad = function (sceneFilename) {
  53969. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  53970. return sceneFilename.substr(5);
  53971. }
  53972. return null;
  53973. };
  53974. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  53975. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  53976. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  53977. var plugin;
  53978. if (registeredPlugin.plugin.createPlugin) {
  53979. plugin = registeredPlugin.plugin.createPlugin();
  53980. }
  53981. else {
  53982. plugin = registeredPlugin.plugin;
  53983. }
  53984. var useArrayBuffer = registeredPlugin.isBinary;
  53985. var database;
  53986. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  53987. var dataCallback = function (data, responseURL) {
  53988. if (scene.isDisposed) {
  53989. onError("Scene has been disposed");
  53990. return;
  53991. }
  53992. scene.database = database;
  53993. onSuccess(plugin, data, responseURL);
  53994. };
  53995. var request = null;
  53996. var pluginDisposed = false;
  53997. var onDisposeObservable = plugin.onDisposeObservable;
  53998. if (onDisposeObservable) {
  53999. onDisposeObservable.add(function () {
  54000. pluginDisposed = true;
  54001. if (request) {
  54002. request.abort();
  54003. request = null;
  54004. }
  54005. onDispose();
  54006. });
  54007. }
  54008. var manifestChecked = function () {
  54009. if (pluginDisposed) {
  54010. return;
  54011. }
  54012. var url = rootUrl + sceneFilename;
  54013. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  54014. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  54015. } : undefined, database, useArrayBuffer, function (request, exception) {
  54016. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  54017. });
  54018. };
  54019. if (directLoad) {
  54020. dataCallback(directLoad);
  54021. return plugin;
  54022. }
  54023. if (rootUrl.indexOf("file:") === -1) {
  54024. if (scene.getEngine().enableOfflineSupport) {
  54025. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  54026. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  54027. }
  54028. else {
  54029. manifestChecked();
  54030. }
  54031. }
  54032. else {
  54033. var fileOrString = sceneFilename;
  54034. if (fileOrString.name) {
  54035. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  54036. }
  54037. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  54038. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  54039. }
  54040. else {
  54041. onError("Unable to find file named " + sceneFilename);
  54042. }
  54043. }
  54044. return plugin;
  54045. };
  54046. // Public functions
  54047. SceneLoader.GetPluginForExtension = function (extension) {
  54048. return SceneLoader._getPluginForExtension(extension).plugin;
  54049. };
  54050. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  54051. return !!SceneLoader._registeredPlugins[extension];
  54052. };
  54053. SceneLoader.RegisterPlugin = function (plugin) {
  54054. if (typeof plugin.extensions === "string") {
  54055. var extension = plugin.extensions;
  54056. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  54057. plugin: plugin,
  54058. isBinary: false
  54059. };
  54060. }
  54061. else {
  54062. var extensions = plugin.extensions;
  54063. Object.keys(extensions).forEach(function (extension) {
  54064. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  54065. plugin: plugin,
  54066. isBinary: extensions[extension].isBinary
  54067. };
  54068. });
  54069. }
  54070. };
  54071. /**
  54072. * Import meshes into a scene
  54073. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  54074. * @param rootUrl a string that defines the root url for scene and resources
  54075. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  54076. * @param scene the instance of BABYLON.Scene to append to
  54077. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  54078. * @param onProgress a callback with a progress event for each file being loaded
  54079. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  54080. */
  54081. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  54082. if (onSuccess === void 0) { onSuccess = null; }
  54083. if (onProgress === void 0) { onProgress = null; }
  54084. if (onError === void 0) { onError = null; }
  54085. if (pluginExtension === void 0) { pluginExtension = null; }
  54086. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  54087. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  54088. return null;
  54089. }
  54090. var loadingToken = {};
  54091. scene._addPendingData(loadingToken);
  54092. var disposeHandler = function () {
  54093. scene._removePendingData(loadingToken);
  54094. };
  54095. var errorHandler = function (message, exception) {
  54096. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  54097. if (onError) {
  54098. onError(scene, errorMessage, exception);
  54099. }
  54100. else {
  54101. BABYLON.Tools.Error(errorMessage);
  54102. // should the exception be thrown?
  54103. }
  54104. disposeHandler();
  54105. };
  54106. var progressHandler = onProgress ? function (event) {
  54107. try {
  54108. onProgress(event);
  54109. }
  54110. catch (e) {
  54111. errorHandler("Error in onProgress callback", e);
  54112. }
  54113. } : undefined;
  54114. var successHandler = function (meshes, particleSystems, skeletons) {
  54115. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  54116. if (onSuccess) {
  54117. try {
  54118. onSuccess(meshes, particleSystems, skeletons);
  54119. }
  54120. catch (e) {
  54121. errorHandler("Error in onSuccess callback", e);
  54122. }
  54123. }
  54124. scene._removePendingData(loadingToken);
  54125. };
  54126. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  54127. if (plugin.rewriteRootURL) {
  54128. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  54129. }
  54130. if (plugin.importMesh) {
  54131. var syncedPlugin = plugin;
  54132. var meshes = new Array();
  54133. var particleSystems = new Array();
  54134. var skeletons = new Array();
  54135. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  54136. return;
  54137. }
  54138. scene.loadingPluginName = plugin.name;
  54139. successHandler(meshes, particleSystems, skeletons);
  54140. }
  54141. else {
  54142. var asyncedPlugin = plugin;
  54143. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  54144. scene.loadingPluginName = plugin.name;
  54145. successHandler(meshes, particleSystems, skeletons);
  54146. }, progressHandler, errorHandler);
  54147. }
  54148. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  54149. };
  54150. /**
  54151. * Load a scene
  54152. * @param rootUrl a string that defines the root url for scene and resources
  54153. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  54154. * @param engine is the instance of BABYLON.Engine to use to create the scene
  54155. * @param onSuccess a callback with the scene when import succeeds
  54156. * @param onProgress a callback with a progress event for each file being loaded
  54157. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  54158. */
  54159. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  54160. if (onSuccess === void 0) { onSuccess = null; }
  54161. if (onProgress === void 0) { onProgress = null; }
  54162. if (onError === void 0) { onError = null; }
  54163. if (pluginExtension === void 0) { pluginExtension = null; }
  54164. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  54165. };
  54166. /**
  54167. * Append a scene
  54168. * @param rootUrl a string that defines the root url for scene and resources
  54169. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  54170. * @param scene is the instance of BABYLON.Scene to append to
  54171. * @param onSuccess a callback with the scene when import succeeds
  54172. * @param onProgress a callback with a progress event for each file being loaded
  54173. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  54174. */
  54175. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  54176. if (onSuccess === void 0) { onSuccess = null; }
  54177. if (onProgress === void 0) { onProgress = null; }
  54178. if (onError === void 0) { onError = null; }
  54179. if (pluginExtension === void 0) { pluginExtension = null; }
  54180. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  54181. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  54182. return null;
  54183. }
  54184. if (SceneLoader.ShowLoadingScreen) {
  54185. scene.getEngine().displayLoadingUI();
  54186. }
  54187. var loadingToken = {};
  54188. scene._addPendingData(loadingToken);
  54189. var disposeHandler = function () {
  54190. scene._removePendingData(loadingToken);
  54191. scene.getEngine().hideLoadingUI();
  54192. };
  54193. var errorHandler = function (message, exception) {
  54194. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  54195. if (onError) {
  54196. onError(scene, errorMessage, exception);
  54197. }
  54198. else {
  54199. BABYLON.Tools.Error(errorMessage);
  54200. // should the exception be thrown?
  54201. }
  54202. disposeHandler();
  54203. };
  54204. var progressHandler = onProgress ? function (event) {
  54205. try {
  54206. onProgress(event);
  54207. }
  54208. catch (e) {
  54209. errorHandler("Error in onProgress callback", e);
  54210. }
  54211. } : undefined;
  54212. var successHandler = function () {
  54213. if (onSuccess) {
  54214. try {
  54215. onSuccess(scene);
  54216. }
  54217. catch (e) {
  54218. errorHandler("Error in onSuccess callback", e);
  54219. }
  54220. }
  54221. scene._removePendingData(loadingToken);
  54222. };
  54223. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  54224. if (plugin.load) {
  54225. var syncedPlugin = plugin;
  54226. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  54227. return;
  54228. }
  54229. scene.loadingPluginName = plugin.name;
  54230. successHandler();
  54231. }
  54232. else {
  54233. var asyncedPlugin = plugin;
  54234. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  54235. scene.loadingPluginName = plugin.name;
  54236. successHandler();
  54237. }, progressHandler, errorHandler);
  54238. }
  54239. if (SceneLoader.ShowLoadingScreen) {
  54240. scene.executeWhenReady(function () {
  54241. scene.getEngine().hideLoadingUI();
  54242. });
  54243. }
  54244. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  54245. };
  54246. // Flags
  54247. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  54248. SceneLoader._ShowLoadingScreen = true;
  54249. SceneLoader._CleanBoneMatrixWeights = false;
  54250. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  54251. // Members
  54252. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  54253. SceneLoader._registeredPlugins = {};
  54254. return SceneLoader;
  54255. }());
  54256. BABYLON.SceneLoader = SceneLoader;
  54257. ;
  54258. })(BABYLON || (BABYLON = {}));
  54259. //# sourceMappingURL=babylon.sceneLoader.js.map
  54260. var BABYLON;
  54261. (function (BABYLON) {
  54262. var Internals;
  54263. (function (Internals) {
  54264. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  54265. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  54266. var parsedMaterial = parsedData.materials[index];
  54267. if (parsedMaterial.id === id) {
  54268. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  54269. }
  54270. }
  54271. return null;
  54272. };
  54273. var isDescendantOf = function (mesh, names, hierarchyIds) {
  54274. for (var i in names) {
  54275. if (mesh.name === names[i]) {
  54276. hierarchyIds.push(mesh.id);
  54277. return true;
  54278. }
  54279. }
  54280. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  54281. hierarchyIds.push(mesh.id);
  54282. return true;
  54283. }
  54284. return false;
  54285. };
  54286. var logOperation = function (operation, producer) {
  54287. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  54288. };
  54289. BABYLON.SceneLoader.RegisterPlugin({
  54290. name: "babylon.js",
  54291. extensions: ".babylon",
  54292. canDirectLoad: function (data) {
  54293. if (data.indexOf("babylon") !== -1) {
  54294. return true;
  54295. }
  54296. return false;
  54297. },
  54298. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  54299. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  54300. // when SceneLoader.debugLogging = true (default), or exception encountered.
  54301. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  54302. // and avoid problems with multiple concurrent .babylon loads.
  54303. var log = "importMesh has failed JSON parse";
  54304. try {
  54305. var parsedData = JSON.parse(data);
  54306. log = "";
  54307. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  54308. if (!meshesNames) {
  54309. meshesNames = null;
  54310. }
  54311. else if (!Array.isArray(meshesNames)) {
  54312. meshesNames = [meshesNames];
  54313. }
  54314. var hierarchyIds = new Array();
  54315. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  54316. var loadedSkeletonsIds = [];
  54317. var loadedMaterialsIds = [];
  54318. var index;
  54319. var cache;
  54320. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  54321. var parsedMesh = parsedData.meshes[index];
  54322. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  54323. if (meshesNames !== null) {
  54324. // Remove found mesh name from list.
  54325. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  54326. }
  54327. //Geometry?
  54328. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  54329. //does the file contain geometries?
  54330. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  54331. //find the correct geometry and add it to the scene
  54332. var found = false;
  54333. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  54334. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  54335. return;
  54336. }
  54337. else {
  54338. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  54339. if (parsedGeometryData.id === parsedMesh.geometryId) {
  54340. switch (geometryType) {
  54341. case "boxes":
  54342. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  54343. break;
  54344. case "spheres":
  54345. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  54346. break;
  54347. case "cylinders":
  54348. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  54349. break;
  54350. case "toruses":
  54351. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  54352. break;
  54353. case "grounds":
  54354. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  54355. break;
  54356. case "planes":
  54357. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  54358. break;
  54359. case "torusKnots":
  54360. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  54361. break;
  54362. case "vertexData":
  54363. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  54364. break;
  54365. }
  54366. found = true;
  54367. }
  54368. });
  54369. }
  54370. });
  54371. if (found === false) {
  54372. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  54373. }
  54374. }
  54375. }
  54376. // Material ?
  54377. if (parsedMesh.materialId) {
  54378. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  54379. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  54380. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  54381. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  54382. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  54383. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  54384. var subMatId = parsedMultiMaterial.materials[matIndex];
  54385. loadedMaterialsIds.push(subMatId);
  54386. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  54387. log += "\n\tMaterial " + mat.toString(fullDetails);
  54388. }
  54389. loadedMaterialsIds.push(parsedMultiMaterial.id);
  54390. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  54391. materialFound = true;
  54392. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  54393. break;
  54394. }
  54395. }
  54396. }
  54397. if (materialFound === false) {
  54398. loadedMaterialsIds.push(parsedMesh.materialId);
  54399. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  54400. if (!mat) {
  54401. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  54402. }
  54403. else {
  54404. log += "\n\tMaterial " + mat.toString(fullDetails);
  54405. }
  54406. }
  54407. }
  54408. // Skeleton ?
  54409. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  54410. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  54411. if (skeletonAlreadyLoaded === false) {
  54412. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  54413. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  54414. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  54415. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  54416. skeletons.push(skeleton);
  54417. loadedSkeletonsIds.push(parsedSkeleton.id);
  54418. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  54419. }
  54420. }
  54421. }
  54422. }
  54423. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  54424. meshes.push(mesh);
  54425. log += "\n\tMesh " + mesh.toString(fullDetails);
  54426. }
  54427. }
  54428. // Connecting parents
  54429. var currentMesh;
  54430. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  54431. currentMesh = scene.meshes[index];
  54432. if (currentMesh._waitingParentId) {
  54433. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  54434. currentMesh._waitingParentId = null;
  54435. }
  54436. }
  54437. // freeze and compute world matrix application
  54438. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  54439. currentMesh = scene.meshes[index];
  54440. if (currentMesh._waitingFreezeWorldMatrix) {
  54441. currentMesh.freezeWorldMatrix();
  54442. currentMesh._waitingFreezeWorldMatrix = null;
  54443. }
  54444. else {
  54445. currentMesh.computeWorldMatrix(true);
  54446. }
  54447. }
  54448. }
  54449. // Particles
  54450. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  54451. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  54452. var parsedParticleSystem = parsedData.particleSystems[index];
  54453. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  54454. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  54455. }
  54456. }
  54457. }
  54458. return true;
  54459. }
  54460. catch (err) {
  54461. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  54462. if (onError) {
  54463. onError(msg, err);
  54464. }
  54465. else {
  54466. BABYLON.Tools.Log(msg);
  54467. throw err;
  54468. }
  54469. }
  54470. finally {
  54471. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  54472. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  54473. }
  54474. }
  54475. return false;
  54476. },
  54477. load: function (scene, data, rootUrl, onError) {
  54478. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  54479. // when SceneLoader.debugLogging = true (default), or exception encountered.
  54480. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  54481. // and avoid problems with multiple concurrent .babylon loads.
  54482. var log = "importScene has failed JSON parse";
  54483. try {
  54484. var parsedData = JSON.parse(data);
  54485. log = "";
  54486. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  54487. // Scene
  54488. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  54489. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  54490. }
  54491. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  54492. scene.autoClear = parsedData.autoClear;
  54493. }
  54494. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  54495. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  54496. }
  54497. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  54498. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  54499. }
  54500. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  54501. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  54502. }
  54503. // Fog
  54504. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  54505. scene.fogMode = parsedData.fogMode;
  54506. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  54507. scene.fogStart = parsedData.fogStart;
  54508. scene.fogEnd = parsedData.fogEnd;
  54509. scene.fogDensity = parsedData.fogDensity;
  54510. log += "\tFog mode for scene: ";
  54511. switch (scene.fogMode) {
  54512. // getters not compiling, so using hardcoded
  54513. case 1:
  54514. log += "exp\n";
  54515. break;
  54516. case 2:
  54517. log += "exp2\n";
  54518. break;
  54519. case 3:
  54520. log += "linear\n";
  54521. break;
  54522. }
  54523. }
  54524. //Physics
  54525. if (parsedData.physicsEnabled) {
  54526. var physicsPlugin;
  54527. if (parsedData.physicsEngine === "cannon") {
  54528. physicsPlugin = new BABYLON.CannonJSPlugin();
  54529. }
  54530. else if (parsedData.physicsEngine === "oimo") {
  54531. physicsPlugin = new BABYLON.OimoJSPlugin();
  54532. }
  54533. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  54534. //else - default engine, which is currently oimo
  54535. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  54536. scene.enablePhysics(physicsGravity, physicsPlugin);
  54537. }
  54538. // Metadata
  54539. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  54540. scene.metadata = parsedData.metadata;
  54541. }
  54542. //collisions, if defined. otherwise, default is true
  54543. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  54544. scene.collisionsEnabled = parsedData.collisionsEnabled;
  54545. }
  54546. scene.workerCollisions = !!parsedData.workerCollisions;
  54547. var index;
  54548. var cache;
  54549. // Lights
  54550. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  54551. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  54552. var parsedLight = parsedData.lights[index];
  54553. var light = BABYLON.Light.Parse(parsedLight, scene);
  54554. if (light) {
  54555. log += (index === 0 ? "\n\tLights:" : "");
  54556. log += "\n\t\t" + light.toString(fullDetails);
  54557. }
  54558. }
  54559. }
  54560. // Animations
  54561. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  54562. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  54563. var parsedAnimation = parsedData.animations[index];
  54564. var animation = BABYLON.Animation.Parse(parsedAnimation);
  54565. scene.animations.push(animation);
  54566. log += (index === 0 ? "\n\tAnimations:" : "");
  54567. log += "\n\t\t" + animation.toString(fullDetails);
  54568. }
  54569. }
  54570. if (parsedData.autoAnimate) {
  54571. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  54572. }
  54573. // Materials
  54574. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  54575. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  54576. var parsedMaterial = parsedData.materials[index];
  54577. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  54578. log += (index === 0 ? "\n\tMaterials:" : "");
  54579. log += "\n\t\t" + mat.toString(fullDetails);
  54580. }
  54581. }
  54582. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  54583. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  54584. var parsedMultiMaterial = parsedData.multiMaterials[index];
  54585. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  54586. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  54587. log += "\n\t\t" + mmat.toString(fullDetails);
  54588. }
  54589. }
  54590. // Morph targets
  54591. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  54592. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  54593. var managerData = _a[_i];
  54594. BABYLON.MorphTargetManager.Parse(managerData, scene);
  54595. }
  54596. }
  54597. // Skeletons
  54598. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  54599. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  54600. var parsedSkeleton = parsedData.skeletons[index];
  54601. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  54602. log += (index === 0 ? "\n\tSkeletons:" : "");
  54603. log += "\n\t\t" + skeleton.toString(fullDetails);
  54604. }
  54605. }
  54606. // Geometries
  54607. var geometries = parsedData.geometries;
  54608. if (geometries !== undefined && geometries !== null) {
  54609. // Boxes
  54610. var boxes = geometries.boxes;
  54611. if (boxes !== undefined && boxes !== null) {
  54612. for (index = 0, cache = boxes.length; index < cache; index++) {
  54613. var parsedBox = boxes[index];
  54614. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  54615. }
  54616. }
  54617. // Spheres
  54618. var spheres = geometries.spheres;
  54619. if (spheres !== undefined && spheres !== null) {
  54620. for (index = 0, cache = spheres.length; index < cache; index++) {
  54621. var parsedSphere = spheres[index];
  54622. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  54623. }
  54624. }
  54625. // Cylinders
  54626. var cylinders = geometries.cylinders;
  54627. if (cylinders !== undefined && cylinders !== null) {
  54628. for (index = 0, cache = cylinders.length; index < cache; index++) {
  54629. var parsedCylinder = cylinders[index];
  54630. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  54631. }
  54632. }
  54633. // Toruses
  54634. var toruses = geometries.toruses;
  54635. if (toruses !== undefined && toruses !== null) {
  54636. for (index = 0, cache = toruses.length; index < cache; index++) {
  54637. var parsedTorus = toruses[index];
  54638. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  54639. }
  54640. }
  54641. // Grounds
  54642. var grounds = geometries.grounds;
  54643. if (grounds !== undefined && grounds !== null) {
  54644. for (index = 0, cache = grounds.length; index < cache; index++) {
  54645. var parsedGround = grounds[index];
  54646. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  54647. }
  54648. }
  54649. // Planes
  54650. var planes = geometries.planes;
  54651. if (planes !== undefined && planes !== null) {
  54652. for (index = 0, cache = planes.length; index < cache; index++) {
  54653. var parsedPlane = planes[index];
  54654. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  54655. }
  54656. }
  54657. // TorusKnots
  54658. var torusKnots = geometries.torusKnots;
  54659. if (torusKnots !== undefined && torusKnots !== null) {
  54660. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  54661. var parsedTorusKnot = torusKnots[index];
  54662. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  54663. }
  54664. }
  54665. // VertexData
  54666. var vertexData = geometries.vertexData;
  54667. if (vertexData !== undefined && vertexData !== null) {
  54668. for (index = 0, cache = vertexData.length; index < cache; index++) {
  54669. var parsedVertexData = vertexData[index];
  54670. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  54671. }
  54672. }
  54673. }
  54674. // Transform nodes
  54675. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  54676. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  54677. var parsedTransformNode = parsedData.transformNodes[index];
  54678. BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  54679. }
  54680. }
  54681. // Meshes
  54682. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  54683. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  54684. var parsedMesh = parsedData.meshes[index];
  54685. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  54686. log += (index === 0 ? "\n\tMeshes:" : "");
  54687. log += "\n\t\t" + mesh.toString(fullDetails);
  54688. }
  54689. }
  54690. // Cameras
  54691. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  54692. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  54693. var parsedCamera = parsedData.cameras[index];
  54694. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  54695. log += (index === 0 ? "\n\tCameras:" : "");
  54696. log += "\n\t\t" + camera.toString(fullDetails);
  54697. }
  54698. }
  54699. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  54700. scene.setActiveCameraByID(parsedData.activeCameraID);
  54701. }
  54702. // Browsing all the graph to connect the dots
  54703. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  54704. var camera = scene.cameras[index];
  54705. if (camera._waitingParentId) {
  54706. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  54707. camera._waitingParentId = null;
  54708. }
  54709. }
  54710. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  54711. var light_1 = scene.lights[index];
  54712. if (light_1 && light_1._waitingParentId) {
  54713. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  54714. light_1._waitingParentId = null;
  54715. }
  54716. }
  54717. // Sounds
  54718. var loadedSounds = [];
  54719. var loadedSound;
  54720. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  54721. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  54722. var parsedSound = parsedData.sounds[index];
  54723. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  54724. if (!parsedSound.url)
  54725. parsedSound.url = parsedSound.name;
  54726. if (!loadedSounds[parsedSound.url]) {
  54727. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  54728. loadedSounds[parsedSound.url] = loadedSound;
  54729. }
  54730. else {
  54731. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  54732. }
  54733. }
  54734. else {
  54735. new BABYLON.Sound(parsedSound.name, null, scene);
  54736. }
  54737. }
  54738. }
  54739. loadedSounds = [];
  54740. // Connect parents & children and parse actions
  54741. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  54742. var transformNode = scene.transformNodes[index];
  54743. if (transformNode._waitingParentId) {
  54744. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  54745. transformNode._waitingParentId = null;
  54746. }
  54747. }
  54748. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  54749. var mesh = scene.meshes[index];
  54750. if (mesh._waitingParentId) {
  54751. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  54752. mesh._waitingParentId = null;
  54753. }
  54754. if (mesh._waitingActions) {
  54755. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  54756. mesh._waitingActions = null;
  54757. }
  54758. }
  54759. // freeze world matrix application
  54760. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  54761. var currentMesh = scene.meshes[index];
  54762. if (currentMesh._waitingFreezeWorldMatrix) {
  54763. currentMesh.freezeWorldMatrix();
  54764. currentMesh._waitingFreezeWorldMatrix = null;
  54765. }
  54766. else {
  54767. currentMesh.computeWorldMatrix(true);
  54768. }
  54769. }
  54770. // Particles Systems
  54771. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  54772. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  54773. var parsedParticleSystem = parsedData.particleSystems[index];
  54774. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  54775. }
  54776. }
  54777. // Environment texture
  54778. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  54779. scene.environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  54780. if (parsedData.createDefaultSkybox === true) {
  54781. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  54782. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  54783. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  54784. }
  54785. }
  54786. // Lens flares
  54787. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  54788. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  54789. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  54790. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  54791. }
  54792. }
  54793. // Shadows
  54794. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  54795. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  54796. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  54797. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  54798. }
  54799. }
  54800. // Lights exclusions / inclusions
  54801. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  54802. var light_2 = scene.lights[index];
  54803. // Excluded check
  54804. if (light_2._excludedMeshesIds.length > 0) {
  54805. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  54806. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  54807. if (excludedMesh) {
  54808. light_2.excludedMeshes.push(excludedMesh);
  54809. }
  54810. }
  54811. light_2._excludedMeshesIds = [];
  54812. }
  54813. // Included check
  54814. if (light_2._includedOnlyMeshesIds.length > 0) {
  54815. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  54816. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  54817. if (includedOnlyMesh) {
  54818. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  54819. }
  54820. }
  54821. light_2._includedOnlyMeshesIds = [];
  54822. }
  54823. }
  54824. // Actions (scene)
  54825. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  54826. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  54827. }
  54828. // Finish
  54829. return true;
  54830. }
  54831. catch (err) {
  54832. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  54833. if (onError) {
  54834. onError(msg, err);
  54835. }
  54836. else {
  54837. BABYLON.Tools.Log(msg);
  54838. throw err;
  54839. }
  54840. }
  54841. finally {
  54842. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  54843. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  54844. }
  54845. }
  54846. return false;
  54847. }
  54848. });
  54849. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  54850. })(BABYLON || (BABYLON = {}));
  54851. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  54852. var BABYLON;
  54853. (function (BABYLON) {
  54854. var FilesInput = /** @class */ (function () {
  54855. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  54856. this.onProcessFileCallback = function () { return true; };
  54857. this._engine = engine;
  54858. this._currentScene = scene;
  54859. this._sceneLoadedCallback = sceneLoadedCallback;
  54860. this._progressCallback = progressCallback;
  54861. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  54862. this._textureLoadingCallback = textureLoadingCallback;
  54863. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  54864. this._onReloadCallback = onReloadCallback;
  54865. this._errorCallback = errorCallback;
  54866. }
  54867. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  54868. var _this = this;
  54869. if (elementToMonitor) {
  54870. this._elementToMonitor = elementToMonitor;
  54871. this._dragEnterHandler = function (e) { _this.drag(e); };
  54872. this._dragOverHandler = function (e) { _this.drag(e); };
  54873. this._dropHandler = function (e) { _this.drop(e); };
  54874. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  54875. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  54876. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  54877. }
  54878. };
  54879. FilesInput.prototype.dispose = function () {
  54880. if (!this._elementToMonitor) {
  54881. return;
  54882. }
  54883. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  54884. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  54885. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  54886. };
  54887. FilesInput.prototype.renderFunction = function () {
  54888. if (this._additionalRenderLoopLogicCallback) {
  54889. this._additionalRenderLoopLogicCallback();
  54890. }
  54891. if (this._currentScene) {
  54892. if (this._textureLoadingCallback) {
  54893. var remaining = this._currentScene.getWaitingItemsCount();
  54894. if (remaining > 0) {
  54895. this._textureLoadingCallback(remaining);
  54896. }
  54897. }
  54898. this._currentScene.render();
  54899. }
  54900. };
  54901. FilesInput.prototype.drag = function (e) {
  54902. e.stopPropagation();
  54903. e.preventDefault();
  54904. };
  54905. FilesInput.prototype.drop = function (eventDrop) {
  54906. eventDrop.stopPropagation();
  54907. eventDrop.preventDefault();
  54908. this.loadFiles(eventDrop);
  54909. };
  54910. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  54911. var _this = this;
  54912. var reader = folder.createReader();
  54913. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  54914. reader.readEntries(function (entries) {
  54915. remaining.count += entries.length;
  54916. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  54917. var entry = entries_1[_i];
  54918. if (entry.isFile) {
  54919. entry.file(function (file) {
  54920. file.correctName = relativePath + file.name;
  54921. files.push(file);
  54922. if (--remaining.count === 0) {
  54923. callback();
  54924. }
  54925. });
  54926. }
  54927. else if (entry.isDirectory) {
  54928. _this._traverseFolder(entry, files, remaining, callback);
  54929. }
  54930. }
  54931. if (--remaining.count) {
  54932. callback();
  54933. }
  54934. });
  54935. };
  54936. FilesInput.prototype._processFiles = function (files) {
  54937. for (var i = 0; i < files.length; i++) {
  54938. var name = files[i].correctName.toLowerCase();
  54939. var extension = name.split('.').pop();
  54940. if (!this.onProcessFileCallback(files[i], name, extension)) {
  54941. continue;
  54942. }
  54943. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  54944. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  54945. this._sceneFileToLoad = files[i];
  54946. }
  54947. else {
  54948. FilesInput.FilesToLoad[name] = files[i];
  54949. }
  54950. }
  54951. };
  54952. FilesInput.prototype.loadFiles = function (event) {
  54953. var _this = this;
  54954. if (this._startingProcessingFilesCallback)
  54955. this._startingProcessingFilesCallback();
  54956. // Handling data transfer via drag'n'drop
  54957. if (event && event.dataTransfer && event.dataTransfer.files) {
  54958. this._filesToLoad = event.dataTransfer.files;
  54959. }
  54960. // Handling files from input files
  54961. if (event && event.target && event.target.files) {
  54962. this._filesToLoad = event.target.files;
  54963. }
  54964. if (this._filesToLoad && this._filesToLoad.length > 0) {
  54965. var files_1 = new Array();
  54966. var folders = [];
  54967. var items = event.dataTransfer ? event.dataTransfer.items : null;
  54968. for (var i = 0; i < this._filesToLoad.length; i++) {
  54969. var fileToLoad = this._filesToLoad[i];
  54970. var name_1 = fileToLoad.name.toLowerCase();
  54971. var entry = void 0;
  54972. fileToLoad.correctName = name_1;
  54973. if (items) {
  54974. var item = items[i];
  54975. if (item.getAsEntry) {
  54976. entry = item.getAsEntry();
  54977. }
  54978. else if (item.webkitGetAsEntry) {
  54979. entry = item.webkitGetAsEntry();
  54980. }
  54981. }
  54982. if (!entry) {
  54983. files_1.push(fileToLoad);
  54984. }
  54985. else {
  54986. if (entry.isDirectory) {
  54987. folders.push(entry);
  54988. }
  54989. else {
  54990. files_1.push(fileToLoad);
  54991. }
  54992. }
  54993. }
  54994. if (folders.length === 0) {
  54995. this._processFiles(files_1);
  54996. this._processReload();
  54997. }
  54998. else {
  54999. var remaining = { count: folders.length };
  55000. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  55001. var folder = folders_1[_i];
  55002. this._traverseFolder(folder, files_1, remaining, function () {
  55003. _this._processFiles(files_1);
  55004. if (remaining.count === 0) {
  55005. _this._processReload();
  55006. }
  55007. });
  55008. }
  55009. }
  55010. }
  55011. };
  55012. FilesInput.prototype._processReload = function () {
  55013. if (this._onReloadCallback) {
  55014. this._onReloadCallback(this._sceneFileToLoad);
  55015. }
  55016. else {
  55017. this.reload();
  55018. }
  55019. };
  55020. FilesInput.prototype.reload = function () {
  55021. var _this = this;
  55022. // If a scene file has been provided
  55023. if (this._sceneFileToLoad) {
  55024. if (this._currentScene) {
  55025. if (BABYLON.Tools.errorsCount > 0) {
  55026. BABYLON.Tools.ClearLogCache();
  55027. }
  55028. this._engine.stopRenderLoop();
  55029. this._currentScene.dispose();
  55030. }
  55031. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  55032. _this._currentScene = newScene;
  55033. if (_this._sceneLoadedCallback) {
  55034. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  55035. }
  55036. // Wait for textures and shaders to be ready
  55037. _this._currentScene.executeWhenReady(function () {
  55038. _this._engine.runRenderLoop(function () {
  55039. _this.renderFunction();
  55040. });
  55041. });
  55042. }, function (progress) {
  55043. if (_this._progressCallback) {
  55044. _this._progressCallback(progress);
  55045. }
  55046. }, function (scene, message) {
  55047. _this._currentScene = scene;
  55048. if (_this._errorCallback) {
  55049. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, message);
  55050. }
  55051. });
  55052. }
  55053. else {
  55054. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  55055. }
  55056. };
  55057. FilesInput.FilesToLoad = {};
  55058. return FilesInput;
  55059. }());
  55060. BABYLON.FilesInput = FilesInput;
  55061. })(BABYLON || (BABYLON = {}));
  55062. //# sourceMappingURL=babylon.filesInput.js.map
  55063. var BABYLON;
  55064. (function (BABYLON) {
  55065. /**
  55066. * This class implement a typical dictionary using a string as key and the generic type T as value.
  55067. * The underlying implementation relies on an associative array to ensure the best performances.
  55068. * The value can be anything including 'null' but except 'undefined'
  55069. */
  55070. var StringDictionary = /** @class */ (function () {
  55071. function StringDictionary() {
  55072. this._count = 0;
  55073. this._data = {};
  55074. }
  55075. /**
  55076. * This will clear this dictionary and copy the content from the 'source' one.
  55077. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  55078. * @param source the dictionary to take the content from and copy to this dictionary
  55079. */
  55080. StringDictionary.prototype.copyFrom = function (source) {
  55081. var _this = this;
  55082. this.clear();
  55083. source.forEach(function (t, v) { return _this.add(t, v); });
  55084. };
  55085. /**
  55086. * Get a value based from its key
  55087. * @param key the given key to get the matching value from
  55088. * @return the value if found, otherwise undefined is returned
  55089. */
  55090. StringDictionary.prototype.get = function (key) {
  55091. var val = this._data[key];
  55092. if (val !== undefined) {
  55093. return val;
  55094. }
  55095. return undefined;
  55096. };
  55097. /**
  55098. * Get a value from its key or add it if it doesn't exist.
  55099. * This method will ensure you that a given key/data will be present in the dictionary.
  55100. * @param key the given key to get the matching value from
  55101. * @param factory the factory that will create the value if the key is not present in the dictionary.
  55102. * The factory will only be invoked if there's no data for the given key.
  55103. * @return the value corresponding to the key.
  55104. */
  55105. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  55106. var val = this.get(key);
  55107. if (val !== undefined) {
  55108. return val;
  55109. }
  55110. val = factory(key);
  55111. if (val) {
  55112. this.add(key, val);
  55113. }
  55114. return val;
  55115. };
  55116. /**
  55117. * Get a value from its key if present in the dictionary otherwise add it
  55118. * @param key the key to get the value from
  55119. * @param val if there's no such key/value pair in the dictionary add it with this value
  55120. * @return the value corresponding to the key
  55121. */
  55122. StringDictionary.prototype.getOrAdd = function (key, val) {
  55123. var curVal = this.get(key);
  55124. if (curVal !== undefined) {
  55125. return curVal;
  55126. }
  55127. this.add(key, val);
  55128. return val;
  55129. };
  55130. /**
  55131. * Check if there's a given key in the dictionary
  55132. * @param key the key to check for
  55133. * @return true if the key is present, false otherwise
  55134. */
  55135. StringDictionary.prototype.contains = function (key) {
  55136. return this._data[key] !== undefined;
  55137. };
  55138. /**
  55139. * Add a new key and its corresponding value
  55140. * @param key the key to add
  55141. * @param value the value corresponding to the key
  55142. * @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
  55143. */
  55144. StringDictionary.prototype.add = function (key, value) {
  55145. if (this._data[key] !== undefined) {
  55146. return false;
  55147. }
  55148. this._data[key] = value;
  55149. ++this._count;
  55150. return true;
  55151. };
  55152. StringDictionary.prototype.set = function (key, value) {
  55153. if (this._data[key] === undefined) {
  55154. return false;
  55155. }
  55156. this._data[key] = value;
  55157. return true;
  55158. };
  55159. /**
  55160. * Get the element of the given key and remove it from the dictionary
  55161. * @param key
  55162. */
  55163. StringDictionary.prototype.getAndRemove = function (key) {
  55164. var val = this.get(key);
  55165. if (val !== undefined) {
  55166. delete this._data[key];
  55167. --this._count;
  55168. return val;
  55169. }
  55170. return null;
  55171. };
  55172. /**
  55173. * Remove a key/value from the dictionary.
  55174. * @param key the key to remove
  55175. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  55176. */
  55177. StringDictionary.prototype.remove = function (key) {
  55178. if (this.contains(key)) {
  55179. delete this._data[key];
  55180. --this._count;
  55181. return true;
  55182. }
  55183. return false;
  55184. };
  55185. /**
  55186. * Clear the whole content of the dictionary
  55187. */
  55188. StringDictionary.prototype.clear = function () {
  55189. this._data = {};
  55190. this._count = 0;
  55191. };
  55192. Object.defineProperty(StringDictionary.prototype, "count", {
  55193. get: function () {
  55194. return this._count;
  55195. },
  55196. enumerable: true,
  55197. configurable: true
  55198. });
  55199. /**
  55200. * Execute a callback on each key/val of the dictionary.
  55201. * Note that you can remove any element in this dictionary in the callback implementation
  55202. * @param callback the callback to execute on a given key/value pair
  55203. */
  55204. StringDictionary.prototype.forEach = function (callback) {
  55205. for (var cur in this._data) {
  55206. var val = this._data[cur];
  55207. callback(cur, val);
  55208. }
  55209. };
  55210. /**
  55211. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  55212. * If the callback returns null or undefined the method will iterate to the next key/value pair
  55213. * Note that you can remove any element in this dictionary in the callback implementation
  55214. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  55215. */
  55216. StringDictionary.prototype.first = function (callback) {
  55217. for (var cur in this._data) {
  55218. var val = this._data[cur];
  55219. var res = callback(cur, val);
  55220. if (res) {
  55221. return res;
  55222. }
  55223. }
  55224. return null;
  55225. };
  55226. return StringDictionary;
  55227. }());
  55228. BABYLON.StringDictionary = StringDictionary;
  55229. })(BABYLON || (BABYLON = {}));
  55230. //# sourceMappingURL=babylon.stringDictionary.js.map
  55231. var BABYLON;
  55232. (function (BABYLON) {
  55233. var Tags = /** @class */ (function () {
  55234. function Tags() {
  55235. }
  55236. Tags.EnableFor = function (obj) {
  55237. obj._tags = obj._tags || {};
  55238. obj.hasTags = function () {
  55239. return Tags.HasTags(obj);
  55240. };
  55241. obj.addTags = function (tagsString) {
  55242. return Tags.AddTagsTo(obj, tagsString);
  55243. };
  55244. obj.removeTags = function (tagsString) {
  55245. return Tags.RemoveTagsFrom(obj, tagsString);
  55246. };
  55247. obj.matchesTagsQuery = function (tagsQuery) {
  55248. return Tags.MatchesQuery(obj, tagsQuery);
  55249. };
  55250. };
  55251. Tags.DisableFor = function (obj) {
  55252. delete obj._tags;
  55253. delete obj.hasTags;
  55254. delete obj.addTags;
  55255. delete obj.removeTags;
  55256. delete obj.matchesTagsQuery;
  55257. };
  55258. Tags.HasTags = function (obj) {
  55259. if (!obj._tags) {
  55260. return false;
  55261. }
  55262. return !BABYLON.Tools.IsEmpty(obj._tags);
  55263. };
  55264. Tags.GetTags = function (obj, asString) {
  55265. if (asString === void 0) { asString = true; }
  55266. if (!obj._tags) {
  55267. return null;
  55268. }
  55269. if (asString) {
  55270. var tagsArray = [];
  55271. for (var tag in obj._tags) {
  55272. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  55273. tagsArray.push(tag);
  55274. }
  55275. }
  55276. return tagsArray.join(" ");
  55277. }
  55278. else {
  55279. return obj._tags;
  55280. }
  55281. };
  55282. // the tags 'true' and 'false' are reserved and cannot be used as tags
  55283. // a tag cannot start with '||', '&&', and '!'
  55284. // it cannot contain whitespaces
  55285. Tags.AddTagsTo = function (obj, tagsString) {
  55286. if (!tagsString) {
  55287. return;
  55288. }
  55289. if (typeof tagsString !== "string") {
  55290. return;
  55291. }
  55292. var tags = tagsString.split(" ");
  55293. tags.forEach(function (tag, index, array) {
  55294. Tags._AddTagTo(obj, tag);
  55295. });
  55296. };
  55297. Tags._AddTagTo = function (obj, tag) {
  55298. tag = tag.trim();
  55299. if (tag === "" || tag === "true" || tag === "false") {
  55300. return;
  55301. }
  55302. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  55303. return;
  55304. }
  55305. Tags.EnableFor(obj);
  55306. obj._tags[tag] = true;
  55307. };
  55308. Tags.RemoveTagsFrom = function (obj, tagsString) {
  55309. if (!Tags.HasTags(obj)) {
  55310. return;
  55311. }
  55312. var tags = tagsString.split(" ");
  55313. for (var t in tags) {
  55314. Tags._RemoveTagFrom(obj, tags[t]);
  55315. }
  55316. };
  55317. Tags._RemoveTagFrom = function (obj, tag) {
  55318. delete obj._tags[tag];
  55319. };
  55320. Tags.MatchesQuery = function (obj, tagsQuery) {
  55321. if (tagsQuery === undefined) {
  55322. return true;
  55323. }
  55324. if (tagsQuery === "") {
  55325. return Tags.HasTags(obj);
  55326. }
  55327. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  55328. };
  55329. return Tags;
  55330. }());
  55331. BABYLON.Tags = Tags;
  55332. })(BABYLON || (BABYLON = {}));
  55333. //# sourceMappingURL=babylon.tags.js.map
  55334. var BABYLON;
  55335. (function (BABYLON) {
  55336. var Internals;
  55337. (function (Internals) {
  55338. var AndOrNotEvaluator = /** @class */ (function () {
  55339. function AndOrNotEvaluator() {
  55340. }
  55341. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  55342. if (!query.match(/\([^\(\)]*\)/g)) {
  55343. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  55344. }
  55345. else {
  55346. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  55347. // remove parenthesis
  55348. r = r.slice(1, r.length - 1);
  55349. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  55350. });
  55351. }
  55352. if (query === "true") {
  55353. return true;
  55354. }
  55355. if (query === "false") {
  55356. return false;
  55357. }
  55358. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  55359. };
  55360. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  55361. evaluateCallback = evaluateCallback || (function (r) {
  55362. return r === "true" ? true : false;
  55363. });
  55364. var result;
  55365. var or = parenthesisContent.split("||");
  55366. for (var i in or) {
  55367. if (or.hasOwnProperty(i)) {
  55368. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  55369. var and = ori.split("&&");
  55370. if (and.length > 1) {
  55371. for (var j = 0; j < and.length; ++j) {
  55372. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  55373. if (andj !== "true" && andj !== "false") {
  55374. if (andj[0] === "!") {
  55375. result = !evaluateCallback(andj.substring(1));
  55376. }
  55377. else {
  55378. result = evaluateCallback(andj);
  55379. }
  55380. }
  55381. else {
  55382. result = andj === "true" ? true : false;
  55383. }
  55384. if (!result) {
  55385. ori = "false";
  55386. break;
  55387. }
  55388. }
  55389. }
  55390. if (result || ori === "true") {
  55391. result = true;
  55392. break;
  55393. }
  55394. // result equals false (or undefined)
  55395. if (ori !== "true" && ori !== "false") {
  55396. if (ori[0] === "!") {
  55397. result = !evaluateCallback(ori.substring(1));
  55398. }
  55399. else {
  55400. result = evaluateCallback(ori);
  55401. }
  55402. }
  55403. else {
  55404. result = ori === "true" ? true : false;
  55405. }
  55406. }
  55407. }
  55408. // the whole parenthesis scope is replaced by 'true' or 'false'
  55409. return result ? "true" : "false";
  55410. };
  55411. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  55412. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  55413. // remove whitespaces
  55414. r = r.replace(/[\s]/g, function () { return ""; });
  55415. return r.length % 2 ? "!" : "";
  55416. });
  55417. booleanString = booleanString.trim();
  55418. if (booleanString === "!true") {
  55419. booleanString = "false";
  55420. }
  55421. else if (booleanString === "!false") {
  55422. booleanString = "true";
  55423. }
  55424. return booleanString;
  55425. };
  55426. return AndOrNotEvaluator;
  55427. }());
  55428. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  55429. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  55430. })(BABYLON || (BABYLON = {}));
  55431. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  55432. var BABYLON;
  55433. (function (BABYLON) {
  55434. var Database = /** @class */ (function () {
  55435. function Database(urlToScene, callbackManifestChecked) {
  55436. // Handling various flavors of prefixed version of IndexedDB
  55437. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  55438. this.callbackManifestChecked = callbackManifestChecked;
  55439. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  55440. this.db = null;
  55441. this._enableSceneOffline = false;
  55442. this._enableTexturesOffline = false;
  55443. this.manifestVersionFound = 0;
  55444. this.mustUpdateRessources = false;
  55445. this.hasReachedQuota = false;
  55446. if (!Database.IDBStorageEnabled) {
  55447. this.callbackManifestChecked(true);
  55448. }
  55449. else {
  55450. this.checkManifestFile();
  55451. }
  55452. }
  55453. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  55454. get: function () {
  55455. return this._enableSceneOffline;
  55456. },
  55457. enumerable: true,
  55458. configurable: true
  55459. });
  55460. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  55461. get: function () {
  55462. return this._enableTexturesOffline;
  55463. },
  55464. enumerable: true,
  55465. configurable: true
  55466. });
  55467. Database.prototype.checkManifestFile = function () {
  55468. var _this = this;
  55469. var noManifestFile = function () {
  55470. _this._enableSceneOffline = false;
  55471. _this._enableTexturesOffline = false;
  55472. _this.callbackManifestChecked(false);
  55473. };
  55474. var timeStampUsed = false;
  55475. var manifestURL = this.currentSceneUrl + ".manifest";
  55476. var xhr = new XMLHttpRequest();
  55477. if (navigator.onLine) {
  55478. // Adding a timestamp to by-pass browsers' cache
  55479. timeStampUsed = true;
  55480. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  55481. }
  55482. xhr.open("GET", manifestURL, true);
  55483. xhr.addEventListener("load", function () {
  55484. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  55485. try {
  55486. var manifestFile = JSON.parse(xhr.response);
  55487. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  55488. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  55489. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  55490. _this.manifestVersionFound = manifestFile.version;
  55491. }
  55492. if (_this.callbackManifestChecked) {
  55493. _this.callbackManifestChecked(true);
  55494. }
  55495. }
  55496. catch (ex) {
  55497. noManifestFile();
  55498. }
  55499. }
  55500. else {
  55501. noManifestFile();
  55502. }
  55503. }, false);
  55504. xhr.addEventListener("error", function (event) {
  55505. if (timeStampUsed) {
  55506. timeStampUsed = false;
  55507. // Let's retry without the timeStamp
  55508. // It could fail when coupled with HTML5 Offline API
  55509. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  55510. xhr.open("GET", retryManifestURL, true);
  55511. xhr.send();
  55512. }
  55513. else {
  55514. noManifestFile();
  55515. }
  55516. }, false);
  55517. try {
  55518. xhr.send();
  55519. }
  55520. catch (ex) {
  55521. BABYLON.Tools.Error("Error on XHR send request.");
  55522. this.callbackManifestChecked(false);
  55523. }
  55524. };
  55525. Database.prototype.openAsync = function (successCallback, errorCallback) {
  55526. var _this = this;
  55527. var handleError = function () {
  55528. _this.isSupported = false;
  55529. if (errorCallback)
  55530. errorCallback();
  55531. };
  55532. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  55533. // Your browser doesn't support IndexedDB
  55534. this.isSupported = false;
  55535. if (errorCallback)
  55536. errorCallback();
  55537. }
  55538. else {
  55539. // If the DB hasn't been opened or created yet
  55540. if (!this.db) {
  55541. this.hasReachedQuota = false;
  55542. this.isSupported = true;
  55543. var request = this.idbFactory.open("babylonjs", 1);
  55544. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  55545. request.onerror = function (event) {
  55546. handleError();
  55547. };
  55548. // executes when a version change transaction cannot complete due to other active transactions
  55549. request.onblocked = function (event) {
  55550. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  55551. handleError();
  55552. };
  55553. // DB has been opened successfully
  55554. request.onsuccess = function (event) {
  55555. _this.db = request.result;
  55556. successCallback();
  55557. };
  55558. // Initialization of the DB. Creating Scenes & Textures stores
  55559. request.onupgradeneeded = function (event) {
  55560. _this.db = (event.target).result;
  55561. if (_this.db) {
  55562. try {
  55563. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  55564. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  55565. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  55566. }
  55567. catch (ex) {
  55568. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  55569. handleError();
  55570. }
  55571. }
  55572. };
  55573. }
  55574. else {
  55575. if (successCallback)
  55576. successCallback();
  55577. }
  55578. }
  55579. };
  55580. Database.prototype.loadImageFromDB = function (url, image) {
  55581. var _this = this;
  55582. var completeURL = Database.ReturnFullUrlLocation(url);
  55583. var saveAndLoadImage = function () {
  55584. if (!_this.hasReachedQuota && _this.db !== null) {
  55585. // the texture is not yet in the DB, let's try to save it
  55586. _this._saveImageIntoDBAsync(completeURL, image);
  55587. }
  55588. else {
  55589. image.src = url;
  55590. }
  55591. };
  55592. if (!this.mustUpdateRessources) {
  55593. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  55594. }
  55595. else {
  55596. saveAndLoadImage();
  55597. }
  55598. };
  55599. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  55600. if (this.isSupported && this.db !== null) {
  55601. var texture;
  55602. var transaction = this.db.transaction(["textures"]);
  55603. transaction.onabort = function (event) {
  55604. image.src = url;
  55605. };
  55606. transaction.oncomplete = function (event) {
  55607. var blobTextureURL;
  55608. if (texture) {
  55609. var URL = window.URL || window.webkitURL;
  55610. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  55611. image.onerror = function () {
  55612. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  55613. image.src = url;
  55614. };
  55615. image.src = blobTextureURL;
  55616. }
  55617. else {
  55618. notInDBCallback();
  55619. }
  55620. };
  55621. var getRequest = transaction.objectStore("textures").get(url);
  55622. getRequest.onsuccess = function (event) {
  55623. texture = (event.target).result;
  55624. };
  55625. getRequest.onerror = function (event) {
  55626. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  55627. image.src = url;
  55628. };
  55629. }
  55630. else {
  55631. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  55632. image.src = url;
  55633. }
  55634. };
  55635. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  55636. var _this = this;
  55637. if (this.isSupported) {
  55638. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  55639. var generateBlobUrl = function () {
  55640. var blobTextureURL;
  55641. if (blob) {
  55642. var URL = window.URL || window.webkitURL;
  55643. try {
  55644. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  55645. }
  55646. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  55647. catch (ex) {
  55648. blobTextureURL = URL.createObjectURL(blob);
  55649. }
  55650. }
  55651. if (blobTextureURL) {
  55652. image.src = blobTextureURL;
  55653. }
  55654. };
  55655. if (Database.IsUASupportingBlobStorage) {
  55656. var xhr = new XMLHttpRequest(), blob;
  55657. xhr.open("GET", url, true);
  55658. xhr.responseType = "blob";
  55659. xhr.addEventListener("load", function () {
  55660. if (xhr.status === 200 && _this.db) {
  55661. // Blob as response (XHR2)
  55662. blob = xhr.response;
  55663. var transaction = _this.db.transaction(["textures"], "readwrite");
  55664. // the transaction could abort because of a QuotaExceededError error
  55665. transaction.onabort = function (event) {
  55666. try {
  55667. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  55668. var srcElement = (event.srcElement || event.target);
  55669. var error = srcElement.error;
  55670. if (error && error.name === "QuotaExceededError") {
  55671. _this.hasReachedQuota = true;
  55672. }
  55673. }
  55674. catch (ex) { }
  55675. generateBlobUrl();
  55676. };
  55677. transaction.oncomplete = function (event) {
  55678. generateBlobUrl();
  55679. };
  55680. var newTexture = { textureUrl: url, data: blob };
  55681. try {
  55682. // Put the blob into the dabase
  55683. var addRequest = transaction.objectStore("textures").put(newTexture);
  55684. addRequest.onsuccess = function (event) {
  55685. };
  55686. addRequest.onerror = function (event) {
  55687. generateBlobUrl();
  55688. };
  55689. }
  55690. catch (ex) {
  55691. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  55692. if (ex.code === 25) {
  55693. Database.IsUASupportingBlobStorage = false;
  55694. }
  55695. image.src = url;
  55696. }
  55697. }
  55698. else {
  55699. image.src = url;
  55700. }
  55701. }, false);
  55702. xhr.addEventListener("error", function (event) {
  55703. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  55704. image.src = url;
  55705. }, false);
  55706. xhr.send();
  55707. }
  55708. else {
  55709. image.src = url;
  55710. }
  55711. }
  55712. else {
  55713. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  55714. image.src = url;
  55715. }
  55716. };
  55717. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  55718. var _this = this;
  55719. var updateVersion = function () {
  55720. // the version is not yet in the DB or we need to update it
  55721. _this._saveVersionIntoDBAsync(url, versionLoaded);
  55722. };
  55723. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  55724. };
  55725. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  55726. var _this = this;
  55727. if (this.isSupported && this.db) {
  55728. var version;
  55729. try {
  55730. var transaction = this.db.transaction(["versions"]);
  55731. transaction.oncomplete = function (event) {
  55732. if (version) {
  55733. // If the version in the JSON file is > than the version in DB
  55734. if (_this.manifestVersionFound > version.data) {
  55735. _this.mustUpdateRessources = true;
  55736. updateInDBCallback();
  55737. }
  55738. else {
  55739. callback(version.data);
  55740. }
  55741. }
  55742. else {
  55743. _this.mustUpdateRessources = true;
  55744. updateInDBCallback();
  55745. }
  55746. };
  55747. transaction.onabort = function (event) {
  55748. callback(-1);
  55749. };
  55750. var getRequest = transaction.objectStore("versions").get(url);
  55751. getRequest.onsuccess = function (event) {
  55752. version = (event.target).result;
  55753. };
  55754. getRequest.onerror = function (event) {
  55755. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  55756. callback(-1);
  55757. };
  55758. }
  55759. catch (ex) {
  55760. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  55761. callback(-1);
  55762. }
  55763. }
  55764. else {
  55765. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  55766. callback(-1);
  55767. }
  55768. };
  55769. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  55770. var _this = this;
  55771. if (this.isSupported && !this.hasReachedQuota && this.db) {
  55772. try {
  55773. // Open a transaction to the database
  55774. var transaction = this.db.transaction(["versions"], "readwrite");
  55775. // the transaction could abort because of a QuotaExceededError error
  55776. transaction.onabort = function (event) {
  55777. try {
  55778. var error = event.srcElement['error'];
  55779. if (error && error.name === "QuotaExceededError") {
  55780. _this.hasReachedQuota = true;
  55781. }
  55782. }
  55783. catch (ex) { }
  55784. callback(-1);
  55785. };
  55786. transaction.oncomplete = function (event) {
  55787. callback(_this.manifestVersionFound);
  55788. };
  55789. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  55790. // Put the scene into the database
  55791. var addRequest = transaction.objectStore("versions").put(newVersion);
  55792. addRequest.onsuccess = function (event) {
  55793. };
  55794. addRequest.onerror = function (event) {
  55795. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  55796. };
  55797. }
  55798. catch (ex) {
  55799. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  55800. callback(-1);
  55801. }
  55802. }
  55803. else {
  55804. callback(-1);
  55805. }
  55806. };
  55807. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  55808. var _this = this;
  55809. var completeUrl = Database.ReturnFullUrlLocation(url);
  55810. var saveAndLoadFile = function () {
  55811. // the scene is not yet in the DB, let's try to save it
  55812. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  55813. };
  55814. this._checkVersionFromDB(completeUrl, function (version) {
  55815. if (version !== -1) {
  55816. if (!_this.mustUpdateRessources) {
  55817. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  55818. }
  55819. else {
  55820. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  55821. }
  55822. }
  55823. else {
  55824. if (errorCallback) {
  55825. errorCallback();
  55826. }
  55827. }
  55828. });
  55829. };
  55830. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  55831. if (this.isSupported && this.db) {
  55832. var targetStore;
  55833. if (url.indexOf(".babylon") !== -1) {
  55834. targetStore = "scenes";
  55835. }
  55836. else {
  55837. targetStore = "textures";
  55838. }
  55839. var file;
  55840. var transaction = this.db.transaction([targetStore]);
  55841. transaction.oncomplete = function (event) {
  55842. if (file) {
  55843. callback(file.data);
  55844. }
  55845. else {
  55846. notInDBCallback();
  55847. }
  55848. };
  55849. transaction.onabort = function (event) {
  55850. notInDBCallback();
  55851. };
  55852. var getRequest = transaction.objectStore(targetStore).get(url);
  55853. getRequest.onsuccess = function (event) {
  55854. file = (event.target).result;
  55855. };
  55856. getRequest.onerror = function (event) {
  55857. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  55858. notInDBCallback();
  55859. };
  55860. }
  55861. else {
  55862. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  55863. callback();
  55864. }
  55865. };
  55866. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  55867. var _this = this;
  55868. if (this.isSupported) {
  55869. var targetStore;
  55870. if (url.indexOf(".babylon") !== -1) {
  55871. targetStore = "scenes";
  55872. }
  55873. else {
  55874. targetStore = "textures";
  55875. }
  55876. // Create XHR
  55877. var xhr = new XMLHttpRequest();
  55878. var fileData;
  55879. xhr.open("GET", url, true);
  55880. if (useArrayBuffer) {
  55881. xhr.responseType = "arraybuffer";
  55882. }
  55883. if (progressCallback) {
  55884. xhr.onprogress = progressCallback;
  55885. }
  55886. xhr.addEventListener("load", function () {
  55887. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  55888. // Blob as response (XHR2)
  55889. //fileData = xhr.responseText;
  55890. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  55891. if (!_this.hasReachedQuota && _this.db) {
  55892. // Open a transaction to the database
  55893. var transaction = _this.db.transaction([targetStore], "readwrite");
  55894. // the transaction could abort because of a QuotaExceededError error
  55895. transaction.onabort = function (event) {
  55896. try {
  55897. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  55898. var error = event.srcElement['error'];
  55899. if (error && error.name === "QuotaExceededError") {
  55900. _this.hasReachedQuota = true;
  55901. }
  55902. }
  55903. catch (ex) { }
  55904. callback(fileData);
  55905. };
  55906. transaction.oncomplete = function (event) {
  55907. callback(fileData);
  55908. };
  55909. var newFile;
  55910. if (targetStore === "scenes") {
  55911. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  55912. }
  55913. else {
  55914. newFile = { textureUrl: url, data: fileData };
  55915. }
  55916. try {
  55917. // Put the scene into the database
  55918. var addRequest = transaction.objectStore(targetStore).put(newFile);
  55919. addRequest.onsuccess = function (event) {
  55920. };
  55921. addRequest.onerror = function (event) {
  55922. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  55923. };
  55924. }
  55925. catch (ex) {
  55926. callback(fileData);
  55927. }
  55928. }
  55929. else {
  55930. callback(fileData);
  55931. }
  55932. }
  55933. else {
  55934. callback();
  55935. }
  55936. }, false);
  55937. xhr.addEventListener("error", function (event) {
  55938. BABYLON.Tools.Error("error on XHR request.");
  55939. callback();
  55940. }, false);
  55941. xhr.send();
  55942. }
  55943. else {
  55944. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  55945. callback();
  55946. }
  55947. };
  55948. Database.IsUASupportingBlobStorage = true;
  55949. Database.IDBStorageEnabled = true;
  55950. Database.parseURL = function (url) {
  55951. var a = document.createElement('a');
  55952. a.href = url;
  55953. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  55954. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  55955. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  55956. return absLocation;
  55957. };
  55958. Database.ReturnFullUrlLocation = function (url) {
  55959. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  55960. return (Database.parseURL(window.location.href) + url);
  55961. }
  55962. else {
  55963. return url;
  55964. }
  55965. };
  55966. return Database;
  55967. }());
  55968. BABYLON.Database = Database;
  55969. })(BABYLON || (BABYLON = {}));
  55970. //# sourceMappingURL=babylon.database.js.map
  55971. var BABYLON;
  55972. (function (BABYLON) {
  55973. var FresnelParameters = /** @class */ (function () {
  55974. function FresnelParameters() {
  55975. this._isEnabled = true;
  55976. this.leftColor = BABYLON.Color3.White();
  55977. this.rightColor = BABYLON.Color3.Black();
  55978. this.bias = 0;
  55979. this.power = 1;
  55980. }
  55981. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  55982. get: function () {
  55983. return this._isEnabled;
  55984. },
  55985. set: function (value) {
  55986. if (this._isEnabled === value) {
  55987. return;
  55988. }
  55989. this._isEnabled = value;
  55990. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  55991. },
  55992. enumerable: true,
  55993. configurable: true
  55994. });
  55995. FresnelParameters.prototype.clone = function () {
  55996. var newFresnelParameters = new FresnelParameters();
  55997. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  55998. return newFresnelParameters;
  55999. };
  56000. FresnelParameters.prototype.serialize = function () {
  56001. var serializationObject = {};
  56002. serializationObject.isEnabled = this.isEnabled;
  56003. serializationObject.leftColor = this.leftColor;
  56004. serializationObject.rightColor = this.rightColor;
  56005. serializationObject.bias = this.bias;
  56006. serializationObject.power = this.power;
  56007. return serializationObject;
  56008. };
  56009. FresnelParameters.Parse = function (parsedFresnelParameters) {
  56010. var fresnelParameters = new FresnelParameters();
  56011. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  56012. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  56013. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  56014. fresnelParameters.bias = parsedFresnelParameters.bias;
  56015. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  56016. return fresnelParameters;
  56017. };
  56018. return FresnelParameters;
  56019. }());
  56020. BABYLON.FresnelParameters = FresnelParameters;
  56021. })(BABYLON || (BABYLON = {}));
  56022. //# sourceMappingURL=babylon.fresnelParameters.js.map
  56023. var BABYLON;
  56024. (function (BABYLON) {
  56025. var MultiMaterial = /** @class */ (function (_super) {
  56026. __extends(MultiMaterial, _super);
  56027. function MultiMaterial(name, scene) {
  56028. var _this = _super.call(this, name, scene, true) || this;
  56029. scene.multiMaterials.push(_this);
  56030. _this.subMaterials = new Array();
  56031. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  56032. return _this;
  56033. }
  56034. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  56035. get: function () {
  56036. return this._subMaterials;
  56037. },
  56038. set: function (value) {
  56039. this._subMaterials = value;
  56040. this._hookArray(value);
  56041. },
  56042. enumerable: true,
  56043. configurable: true
  56044. });
  56045. MultiMaterial.prototype._hookArray = function (array) {
  56046. var _this = this;
  56047. var oldPush = array.push;
  56048. array.push = function () {
  56049. var items = [];
  56050. for (var _i = 0; _i < arguments.length; _i++) {
  56051. items[_i] = arguments[_i];
  56052. }
  56053. var result = oldPush.apply(array, items);
  56054. _this._markAllSubMeshesAsTexturesDirty();
  56055. return result;
  56056. };
  56057. var oldSplice = array.splice;
  56058. array.splice = function (index, deleteCount) {
  56059. var deleted = oldSplice.apply(array, [index, deleteCount]);
  56060. _this._markAllSubMeshesAsTexturesDirty();
  56061. return deleted;
  56062. };
  56063. };
  56064. // Properties
  56065. MultiMaterial.prototype.getSubMaterial = function (index) {
  56066. if (index < 0 || index >= this.subMaterials.length) {
  56067. return this.getScene().defaultMaterial;
  56068. }
  56069. return this.subMaterials[index];
  56070. };
  56071. MultiMaterial.prototype.getActiveTextures = function () {
  56072. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  56073. if (subMaterial) {
  56074. return subMaterial.getActiveTextures();
  56075. }
  56076. else {
  56077. return [];
  56078. }
  56079. }));
  56080. var _a;
  56081. };
  56082. // Methods
  56083. MultiMaterial.prototype.getClassName = function () {
  56084. return "MultiMaterial";
  56085. };
  56086. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  56087. for (var index = 0; index < this.subMaterials.length; index++) {
  56088. var subMaterial = this.subMaterials[index];
  56089. if (subMaterial) {
  56090. if (subMaterial.storeEffectOnSubMeshes) {
  56091. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  56092. return false;
  56093. }
  56094. continue;
  56095. }
  56096. if (!subMaterial.isReady(mesh)) {
  56097. return false;
  56098. }
  56099. }
  56100. }
  56101. return true;
  56102. };
  56103. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  56104. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  56105. for (var index = 0; index < this.subMaterials.length; index++) {
  56106. var subMaterial = null;
  56107. var current = this.subMaterials[index];
  56108. if (cloneChildren && current) {
  56109. subMaterial = current.clone(name + "-" + current.name);
  56110. }
  56111. else {
  56112. subMaterial = this.subMaterials[index];
  56113. }
  56114. newMultiMaterial.subMaterials.push(subMaterial);
  56115. }
  56116. return newMultiMaterial;
  56117. };
  56118. MultiMaterial.prototype.serialize = function () {
  56119. var serializationObject = {};
  56120. serializationObject.name = this.name;
  56121. serializationObject.id = this.id;
  56122. if (BABYLON.Tags) {
  56123. serializationObject.tags = BABYLON.Tags.GetTags(this);
  56124. }
  56125. serializationObject.materials = [];
  56126. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  56127. var subMat = this.subMaterials[matIndex];
  56128. if (subMat) {
  56129. serializationObject.materials.push(subMat.id);
  56130. }
  56131. else {
  56132. serializationObject.materials.push(null);
  56133. }
  56134. }
  56135. return serializationObject;
  56136. };
  56137. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  56138. var scene = this.getScene();
  56139. if (!scene) {
  56140. return;
  56141. }
  56142. var index = scene.multiMaterials.indexOf(this);
  56143. if (index >= 0) {
  56144. scene.multiMaterials.splice(index, 1);
  56145. }
  56146. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  56147. };
  56148. return MultiMaterial;
  56149. }(BABYLON.Material));
  56150. BABYLON.MultiMaterial = MultiMaterial;
  56151. })(BABYLON || (BABYLON = {}));
  56152. //# sourceMappingURL=babylon.multiMaterial.js.map
  56153. var BABYLON;
  56154. (function (BABYLON) {
  56155. var FreeCameraTouchInput = /** @class */ (function () {
  56156. function FreeCameraTouchInput() {
  56157. this._offsetX = null;
  56158. this._offsetY = null;
  56159. this._pointerPressed = new Array();
  56160. this.touchAngularSensibility = 200000.0;
  56161. this.touchMoveSensibility = 250.0;
  56162. }
  56163. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  56164. var _this = this;
  56165. var previousPosition = null;
  56166. if (this._pointerInput === undefined) {
  56167. this._onLostFocus = function (evt) {
  56168. _this._offsetX = null;
  56169. _this._offsetY = null;
  56170. };
  56171. this._pointerInput = function (p, s) {
  56172. var evt = p.event;
  56173. if (evt.pointerType === "mouse") {
  56174. return;
  56175. }
  56176. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  56177. if (!noPreventDefault) {
  56178. evt.preventDefault();
  56179. }
  56180. _this._pointerPressed.push(evt.pointerId);
  56181. if (_this._pointerPressed.length !== 1) {
  56182. return;
  56183. }
  56184. previousPosition = {
  56185. x: evt.clientX,
  56186. y: evt.clientY
  56187. };
  56188. }
  56189. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  56190. if (!noPreventDefault) {
  56191. evt.preventDefault();
  56192. }
  56193. var index = _this._pointerPressed.indexOf(evt.pointerId);
  56194. if (index === -1) {
  56195. return;
  56196. }
  56197. _this._pointerPressed.splice(index, 1);
  56198. if (index != 0) {
  56199. return;
  56200. }
  56201. previousPosition = null;
  56202. _this._offsetX = null;
  56203. _this._offsetY = null;
  56204. }
  56205. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  56206. if (!noPreventDefault) {
  56207. evt.preventDefault();
  56208. }
  56209. if (!previousPosition) {
  56210. return;
  56211. }
  56212. var index = _this._pointerPressed.indexOf(evt.pointerId);
  56213. if (index != 0) {
  56214. return;
  56215. }
  56216. _this._offsetX = evt.clientX - previousPosition.x;
  56217. _this._offsetY = -(evt.clientY - previousPosition.y);
  56218. }
  56219. };
  56220. }
  56221. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  56222. if (this._onLostFocus) {
  56223. element.addEventListener("blur", this._onLostFocus);
  56224. }
  56225. };
  56226. FreeCameraTouchInput.prototype.detachControl = function (element) {
  56227. if (this._pointerInput && element) {
  56228. if (this._observer) {
  56229. this.camera.getScene().onPointerObservable.remove(this._observer);
  56230. this._observer = null;
  56231. }
  56232. if (this._onLostFocus) {
  56233. element.removeEventListener("blur", this._onLostFocus);
  56234. this._onLostFocus = null;
  56235. }
  56236. this._pointerPressed = [];
  56237. this._offsetX = null;
  56238. this._offsetY = null;
  56239. }
  56240. };
  56241. FreeCameraTouchInput.prototype.checkInputs = function () {
  56242. if (this._offsetX && this._offsetY) {
  56243. var camera = this.camera;
  56244. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  56245. if (this._pointerPressed.length > 1) {
  56246. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  56247. }
  56248. else {
  56249. var speed = camera._computeLocalCameraSpeed();
  56250. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  56251. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  56252. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  56253. }
  56254. }
  56255. };
  56256. FreeCameraTouchInput.prototype.getClassName = function () {
  56257. return "FreeCameraTouchInput";
  56258. };
  56259. FreeCameraTouchInput.prototype.getSimpleName = function () {
  56260. return "touch";
  56261. };
  56262. __decorate([
  56263. BABYLON.serialize()
  56264. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  56265. __decorate([
  56266. BABYLON.serialize()
  56267. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  56268. return FreeCameraTouchInput;
  56269. }());
  56270. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  56271. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  56272. })(BABYLON || (BABYLON = {}));
  56273. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  56274. var BABYLON;
  56275. (function (BABYLON) {
  56276. // We're mainly based on the logic defined into the FreeCamera code
  56277. var TouchCamera = /** @class */ (function (_super) {
  56278. __extends(TouchCamera, _super);
  56279. //-- end properties for backward compatibility for inputs
  56280. function TouchCamera(name, position, scene) {
  56281. var _this = _super.call(this, name, position, scene) || this;
  56282. _this.inputs.addTouch();
  56283. _this._setupInputs();
  56284. return _this;
  56285. }
  56286. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  56287. //-- Begin properties for backward compatibility for inputs
  56288. get: function () {
  56289. var touch = this.inputs.attached["touch"];
  56290. if (touch)
  56291. return touch.touchAngularSensibility;
  56292. return 0;
  56293. },
  56294. set: function (value) {
  56295. var touch = this.inputs.attached["touch"];
  56296. if (touch)
  56297. touch.touchAngularSensibility = value;
  56298. },
  56299. enumerable: true,
  56300. configurable: true
  56301. });
  56302. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  56303. get: function () {
  56304. var touch = this.inputs.attached["touch"];
  56305. if (touch)
  56306. return touch.touchMoveSensibility;
  56307. return 0;
  56308. },
  56309. set: function (value) {
  56310. var touch = this.inputs.attached["touch"];
  56311. if (touch)
  56312. touch.touchMoveSensibility = value;
  56313. },
  56314. enumerable: true,
  56315. configurable: true
  56316. });
  56317. TouchCamera.prototype.getClassName = function () {
  56318. return "TouchCamera";
  56319. };
  56320. TouchCamera.prototype._setupInputs = function () {
  56321. var mouse = this.inputs.attached["mouse"];
  56322. if (mouse) {
  56323. mouse.touchEnabled = false;
  56324. }
  56325. };
  56326. return TouchCamera;
  56327. }(BABYLON.FreeCamera));
  56328. BABYLON.TouchCamera = TouchCamera;
  56329. })(BABYLON || (BABYLON = {}));
  56330. //# sourceMappingURL=babylon.touchCamera.js.map
  56331. var BABYLON;
  56332. (function (BABYLON) {
  56333. var ProceduralTexture = /** @class */ (function (_super) {
  56334. __extends(ProceduralTexture, _super);
  56335. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  56336. if (fallbackTexture === void 0) { fallbackTexture = null; }
  56337. if (generateMipMaps === void 0) { generateMipMaps = true; }
  56338. if (isCube === void 0) { isCube = false; }
  56339. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  56340. _this.isCube = isCube;
  56341. _this.isEnabled = true;
  56342. _this._currentRefreshId = -1;
  56343. _this._refreshRate = 1;
  56344. _this._vertexBuffers = {};
  56345. _this._uniforms = new Array();
  56346. _this._samplers = new Array();
  56347. _this._textures = {};
  56348. _this._floats = {};
  56349. _this._floatsArrays = {};
  56350. _this._colors3 = {};
  56351. _this._colors4 = {};
  56352. _this._vectors2 = {};
  56353. _this._vectors3 = {};
  56354. _this._matrices = {};
  56355. _this._fallbackTextureUsed = false;
  56356. scene._proceduralTextures.push(_this);
  56357. _this._engine = scene.getEngine();
  56358. _this.name = name;
  56359. _this.isRenderTarget = true;
  56360. _this._size = size;
  56361. _this._generateMipMaps = generateMipMaps;
  56362. _this.setFragment(fragment);
  56363. _this._fallbackTexture = fallbackTexture;
  56364. if (isCube) {
  56365. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  56366. _this.setFloat("face", 0);
  56367. }
  56368. else {
  56369. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  56370. }
  56371. // VBO
  56372. var vertices = [];
  56373. vertices.push(1, 1);
  56374. vertices.push(-1, 1);
  56375. vertices.push(-1, -1);
  56376. vertices.push(1, -1);
  56377. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  56378. _this._createIndexBuffer();
  56379. return _this;
  56380. }
  56381. ProceduralTexture.prototype._createIndexBuffer = function () {
  56382. var engine = this._engine;
  56383. // Indices
  56384. var indices = [];
  56385. indices.push(0);
  56386. indices.push(1);
  56387. indices.push(2);
  56388. indices.push(0);
  56389. indices.push(2);
  56390. indices.push(3);
  56391. this._indexBuffer = engine.createIndexBuffer(indices);
  56392. };
  56393. ProceduralTexture.prototype._rebuild = function () {
  56394. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  56395. if (vb) {
  56396. vb._rebuild();
  56397. }
  56398. this._createIndexBuffer();
  56399. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  56400. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  56401. }
  56402. };
  56403. ProceduralTexture.prototype.reset = function () {
  56404. if (this._effect === undefined) {
  56405. return;
  56406. }
  56407. var engine = this._engine;
  56408. engine._releaseEffect(this._effect);
  56409. };
  56410. ProceduralTexture.prototype.isReady = function () {
  56411. var _this = this;
  56412. var engine = this._engine;
  56413. var shaders;
  56414. if (!this._fragment) {
  56415. return false;
  56416. }
  56417. if (this._fallbackTextureUsed) {
  56418. return true;
  56419. }
  56420. if (this._fragment.fragmentElement !== undefined) {
  56421. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  56422. }
  56423. else {
  56424. shaders = { vertex: "procedural", fragment: this._fragment };
  56425. }
  56426. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  56427. _this.releaseInternalTexture();
  56428. if (_this._fallbackTexture) {
  56429. _this._texture = _this._fallbackTexture._texture;
  56430. if (_this._texture) {
  56431. _this._texture.incrementReferences();
  56432. }
  56433. }
  56434. _this._fallbackTextureUsed = true;
  56435. });
  56436. return this._effect.isReady();
  56437. };
  56438. ProceduralTexture.prototype.resetRefreshCounter = function () {
  56439. this._currentRefreshId = -1;
  56440. };
  56441. ProceduralTexture.prototype.setFragment = function (fragment) {
  56442. this._fragment = fragment;
  56443. };
  56444. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  56445. get: function () {
  56446. return this._refreshRate;
  56447. },
  56448. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  56449. set: function (value) {
  56450. this._refreshRate = value;
  56451. this.resetRefreshCounter();
  56452. },
  56453. enumerable: true,
  56454. configurable: true
  56455. });
  56456. ProceduralTexture.prototype._shouldRender = function () {
  56457. if (!this.isEnabled || !this.isReady() || !this._texture) {
  56458. return false;
  56459. }
  56460. if (this._fallbackTextureUsed) {
  56461. return false;
  56462. }
  56463. if (this._currentRefreshId === -1) {
  56464. this._currentRefreshId = 1;
  56465. return true;
  56466. }
  56467. if (this.refreshRate === this._currentRefreshId) {
  56468. this._currentRefreshId = 1;
  56469. return true;
  56470. }
  56471. this._currentRefreshId++;
  56472. return false;
  56473. };
  56474. ProceduralTexture.prototype.getRenderSize = function () {
  56475. return this._size;
  56476. };
  56477. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  56478. if (this._fallbackTextureUsed) {
  56479. return;
  56480. }
  56481. this.releaseInternalTexture();
  56482. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  56483. };
  56484. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  56485. if (this._uniforms.indexOf(uniformName) === -1) {
  56486. this._uniforms.push(uniformName);
  56487. }
  56488. };
  56489. ProceduralTexture.prototype.setTexture = function (name, texture) {
  56490. if (this._samplers.indexOf(name) === -1) {
  56491. this._samplers.push(name);
  56492. }
  56493. this._textures[name] = texture;
  56494. return this;
  56495. };
  56496. ProceduralTexture.prototype.setFloat = function (name, value) {
  56497. this._checkUniform(name);
  56498. this._floats[name] = value;
  56499. return this;
  56500. };
  56501. ProceduralTexture.prototype.setFloats = function (name, value) {
  56502. this._checkUniform(name);
  56503. this._floatsArrays[name] = value;
  56504. return this;
  56505. };
  56506. ProceduralTexture.prototype.setColor3 = function (name, value) {
  56507. this._checkUniform(name);
  56508. this._colors3[name] = value;
  56509. return this;
  56510. };
  56511. ProceduralTexture.prototype.setColor4 = function (name, value) {
  56512. this._checkUniform(name);
  56513. this._colors4[name] = value;
  56514. return this;
  56515. };
  56516. ProceduralTexture.prototype.setVector2 = function (name, value) {
  56517. this._checkUniform(name);
  56518. this._vectors2[name] = value;
  56519. return this;
  56520. };
  56521. ProceduralTexture.prototype.setVector3 = function (name, value) {
  56522. this._checkUniform(name);
  56523. this._vectors3[name] = value;
  56524. return this;
  56525. };
  56526. ProceduralTexture.prototype.setMatrix = function (name, value) {
  56527. this._checkUniform(name);
  56528. this._matrices[name] = value;
  56529. return this;
  56530. };
  56531. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  56532. var scene = this.getScene();
  56533. if (!scene) {
  56534. return;
  56535. }
  56536. var engine = this._engine;
  56537. // Render
  56538. engine.enableEffect(this._effect);
  56539. engine.setState(false);
  56540. // Texture
  56541. for (var name in this._textures) {
  56542. this._effect.setTexture(name, this._textures[name]);
  56543. }
  56544. // Float
  56545. for (name in this._floats) {
  56546. this._effect.setFloat(name, this._floats[name]);
  56547. }
  56548. // Floats
  56549. for (name in this._floatsArrays) {
  56550. this._effect.setArray(name, this._floatsArrays[name]);
  56551. }
  56552. // Color3
  56553. for (name in this._colors3) {
  56554. this._effect.setColor3(name, this._colors3[name]);
  56555. }
  56556. // Color4
  56557. for (name in this._colors4) {
  56558. var color = this._colors4[name];
  56559. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  56560. }
  56561. // Vector2
  56562. for (name in this._vectors2) {
  56563. this._effect.setVector2(name, this._vectors2[name]);
  56564. }
  56565. // Vector3
  56566. for (name in this._vectors3) {
  56567. this._effect.setVector3(name, this._vectors3[name]);
  56568. }
  56569. // Matrix
  56570. for (name in this._matrices) {
  56571. this._effect.setMatrix(name, this._matrices[name]);
  56572. }
  56573. if (!this._texture) {
  56574. return;
  56575. }
  56576. if (this.isCube) {
  56577. for (var face = 0; face < 6; face++) {
  56578. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  56579. // VBOs
  56580. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  56581. this._effect.setFloat("face", face);
  56582. // Clear
  56583. engine.clear(scene.clearColor, true, true, true);
  56584. // Draw order
  56585. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  56586. // Mipmaps
  56587. if (face === 5) {
  56588. engine.generateMipMapsForCubemap(this._texture);
  56589. }
  56590. }
  56591. }
  56592. else {
  56593. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  56594. // VBOs
  56595. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  56596. // Clear
  56597. engine.clear(scene.clearColor, true, true, true);
  56598. // Draw order
  56599. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  56600. }
  56601. // Unbind
  56602. engine.unBindFramebuffer(this._texture, this.isCube);
  56603. if (this.onGenerated) {
  56604. this.onGenerated();
  56605. }
  56606. };
  56607. ProceduralTexture.prototype.clone = function () {
  56608. var textureSize = this.getSize();
  56609. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  56610. // Base texture
  56611. newTexture.hasAlpha = this.hasAlpha;
  56612. newTexture.level = this.level;
  56613. // RenderTarget Texture
  56614. newTexture.coordinatesMode = this.coordinatesMode;
  56615. return newTexture;
  56616. };
  56617. ProceduralTexture.prototype.dispose = function () {
  56618. var scene = this.getScene();
  56619. if (!scene) {
  56620. return;
  56621. }
  56622. var index = scene._proceduralTextures.indexOf(this);
  56623. if (index >= 0) {
  56624. scene._proceduralTextures.splice(index, 1);
  56625. }
  56626. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  56627. if (vertexBuffer) {
  56628. vertexBuffer.dispose();
  56629. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  56630. }
  56631. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  56632. this._indexBuffer = null;
  56633. }
  56634. _super.prototype.dispose.call(this);
  56635. };
  56636. return ProceduralTexture;
  56637. }(BABYLON.Texture));
  56638. BABYLON.ProceduralTexture = ProceduralTexture;
  56639. })(BABYLON || (BABYLON = {}));
  56640. //# sourceMappingURL=babylon.proceduralTexture.js.map
  56641. var BABYLON;
  56642. (function (BABYLON) {
  56643. var CustomProceduralTexture = /** @class */ (function (_super) {
  56644. __extends(CustomProceduralTexture, _super);
  56645. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  56646. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  56647. _this._animate = true;
  56648. _this._time = 0;
  56649. _this._texturePath = texturePath;
  56650. //Try to load json
  56651. _this.loadJson(texturePath);
  56652. _this.refreshRate = 1;
  56653. return _this;
  56654. }
  56655. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  56656. var _this = this;
  56657. var noConfigFile = function () {
  56658. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  56659. try {
  56660. _this.setFragment(_this._texturePath);
  56661. }
  56662. catch (ex) {
  56663. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  56664. }
  56665. };
  56666. var configFileUrl = jsonUrl + "/config.json";
  56667. var xhr = new XMLHttpRequest();
  56668. xhr.open("GET", configFileUrl, true);
  56669. xhr.addEventListener("load", function () {
  56670. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  56671. try {
  56672. _this._config = JSON.parse(xhr.response);
  56673. _this.updateShaderUniforms();
  56674. _this.updateTextures();
  56675. _this.setFragment(_this._texturePath + "/custom");
  56676. _this._animate = _this._config.animate;
  56677. _this.refreshRate = _this._config.refreshrate;
  56678. }
  56679. catch (ex) {
  56680. noConfigFile();
  56681. }
  56682. }
  56683. else {
  56684. noConfigFile();
  56685. }
  56686. }, false);
  56687. xhr.addEventListener("error", function () {
  56688. noConfigFile();
  56689. }, false);
  56690. try {
  56691. xhr.send();
  56692. }
  56693. catch (ex) {
  56694. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  56695. }
  56696. };
  56697. CustomProceduralTexture.prototype.isReady = function () {
  56698. if (!_super.prototype.isReady.call(this)) {
  56699. return false;
  56700. }
  56701. for (var name in this._textures) {
  56702. var texture = this._textures[name];
  56703. if (!texture.isReady()) {
  56704. return false;
  56705. }
  56706. }
  56707. return true;
  56708. };
  56709. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  56710. var scene = this.getScene();
  56711. if (this._animate && scene) {
  56712. this._time += scene.getAnimationRatio() * 0.03;
  56713. this.updateShaderUniforms();
  56714. }
  56715. _super.prototype.render.call(this, useCameraPostProcess);
  56716. };
  56717. CustomProceduralTexture.prototype.updateTextures = function () {
  56718. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  56719. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  56720. }
  56721. };
  56722. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  56723. if (this._config) {
  56724. for (var j = 0; j < this._config.uniforms.length; j++) {
  56725. var uniform = this._config.uniforms[j];
  56726. switch (uniform.type) {
  56727. case "float":
  56728. this.setFloat(uniform.name, uniform.value);
  56729. break;
  56730. case "color3":
  56731. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  56732. break;
  56733. case "color4":
  56734. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  56735. break;
  56736. case "vector2":
  56737. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  56738. break;
  56739. case "vector3":
  56740. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  56741. break;
  56742. }
  56743. }
  56744. }
  56745. this.setFloat("time", this._time);
  56746. };
  56747. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  56748. get: function () {
  56749. return this._animate;
  56750. },
  56751. set: function (value) {
  56752. this._animate = value;
  56753. },
  56754. enumerable: true,
  56755. configurable: true
  56756. });
  56757. return CustomProceduralTexture;
  56758. }(BABYLON.ProceduralTexture));
  56759. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  56760. })(BABYLON || (BABYLON = {}));
  56761. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  56762. var BABYLON;
  56763. (function (BABYLON) {
  56764. var FreeCameraGamepadInput = /** @class */ (function () {
  56765. function FreeCameraGamepadInput() {
  56766. this.gamepadAngularSensibility = 200;
  56767. this.gamepadMoveSensibility = 40;
  56768. // private members
  56769. this._cameraTransform = BABYLON.Matrix.Identity();
  56770. this._deltaTransform = BABYLON.Vector3.Zero();
  56771. this._vector3 = BABYLON.Vector3.Zero();
  56772. this._vector2 = BABYLON.Vector2.Zero();
  56773. }
  56774. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  56775. var _this = this;
  56776. var manager = this.camera.getScene().gamepadManager;
  56777. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  56778. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  56779. // prioritize XBOX gamepads.
  56780. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  56781. _this.gamepad = gamepad;
  56782. }
  56783. }
  56784. });
  56785. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  56786. if (_this.gamepad === gamepad) {
  56787. _this.gamepad = null;
  56788. }
  56789. });
  56790. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  56791. };
  56792. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  56793. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  56794. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  56795. this.gamepad = null;
  56796. };
  56797. FreeCameraGamepadInput.prototype.checkInputs = function () {
  56798. if (this.gamepad && this.gamepad.leftStick) {
  56799. var camera = this.camera;
  56800. var LSValues = this.gamepad.leftStick;
  56801. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  56802. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  56803. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  56804. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  56805. var RSValues = this.gamepad.rightStick;
  56806. if (RSValues) {
  56807. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  56808. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  56809. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  56810. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  56811. }
  56812. else {
  56813. RSValues = { x: 0, y: 0 };
  56814. }
  56815. if (!camera.rotationQuaternion) {
  56816. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  56817. }
  56818. else {
  56819. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  56820. }
  56821. var speed = camera._computeLocalCameraSpeed() * 50.0;
  56822. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  56823. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  56824. camera.cameraDirection.addInPlace(this._deltaTransform);
  56825. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  56826. camera.cameraRotation.addInPlace(this._vector2);
  56827. }
  56828. };
  56829. FreeCameraGamepadInput.prototype.getClassName = function () {
  56830. return "FreeCameraGamepadInput";
  56831. };
  56832. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  56833. return "gamepad";
  56834. };
  56835. __decorate([
  56836. BABYLON.serialize()
  56837. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  56838. __decorate([
  56839. BABYLON.serialize()
  56840. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  56841. return FreeCameraGamepadInput;
  56842. }());
  56843. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  56844. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  56845. })(BABYLON || (BABYLON = {}));
  56846. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  56847. var BABYLON;
  56848. (function (BABYLON) {
  56849. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  56850. function ArcRotateCameraGamepadInput() {
  56851. this.gamepadRotationSensibility = 80;
  56852. this.gamepadMoveSensibility = 40;
  56853. }
  56854. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  56855. var _this = this;
  56856. var manager = this.camera.getScene().gamepadManager;
  56857. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  56858. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  56859. // prioritize XBOX gamepads.
  56860. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  56861. _this.gamepad = gamepad;
  56862. }
  56863. }
  56864. });
  56865. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  56866. if (_this.gamepad === gamepad) {
  56867. _this.gamepad = null;
  56868. }
  56869. });
  56870. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  56871. };
  56872. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  56873. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  56874. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  56875. this.gamepad = null;
  56876. };
  56877. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  56878. if (this.gamepad) {
  56879. var camera = this.camera;
  56880. var RSValues = this.gamepad.rightStick;
  56881. if (RSValues) {
  56882. if (RSValues.x != 0) {
  56883. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  56884. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  56885. camera.inertialAlphaOffset += normalizedRX;
  56886. }
  56887. }
  56888. if (RSValues.y != 0) {
  56889. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  56890. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  56891. camera.inertialBetaOffset += normalizedRY;
  56892. }
  56893. }
  56894. }
  56895. var LSValues = this.gamepad.leftStick;
  56896. if (LSValues && LSValues.y != 0) {
  56897. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  56898. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  56899. this.camera.inertialRadiusOffset -= normalizedLY;
  56900. }
  56901. }
  56902. }
  56903. };
  56904. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  56905. return "ArcRotateCameraGamepadInput";
  56906. };
  56907. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  56908. return "gamepad";
  56909. };
  56910. __decorate([
  56911. BABYLON.serialize()
  56912. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  56913. __decorate([
  56914. BABYLON.serialize()
  56915. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  56916. return ArcRotateCameraGamepadInput;
  56917. }());
  56918. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  56919. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  56920. })(BABYLON || (BABYLON = {}));
  56921. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  56922. var BABYLON;
  56923. (function (BABYLON) {
  56924. var GamepadManager = /** @class */ (function () {
  56925. function GamepadManager(_scene) {
  56926. var _this = this;
  56927. this._scene = _scene;
  56928. this._babylonGamepads = [];
  56929. this._oneGamepadConnected = false;
  56930. this._isMonitoring = false;
  56931. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  56932. if (!BABYLON.Tools.IsWindowObjectExist()) {
  56933. this._gamepadEventSupported = false;
  56934. }
  56935. else {
  56936. this._gamepadEventSupported = 'GamepadEvent' in window;
  56937. this._gamepadSupport = (navigator.getGamepads ||
  56938. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  56939. }
  56940. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  56941. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  56942. for (var i in _this._babylonGamepads) {
  56943. var gamepad = _this._babylonGamepads[i];
  56944. if (gamepad && gamepad._isConnected) {
  56945. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  56946. }
  56947. }
  56948. });
  56949. this._onGamepadConnectedEvent = function (evt) {
  56950. var gamepad = evt.gamepad;
  56951. if (gamepad.index in _this._babylonGamepads) {
  56952. if (_this._babylonGamepads[gamepad.index].isConnected) {
  56953. return;
  56954. }
  56955. }
  56956. var newGamepad;
  56957. if (_this._babylonGamepads[gamepad.index]) {
  56958. newGamepad = _this._babylonGamepads[gamepad.index];
  56959. newGamepad.browserGamepad = gamepad;
  56960. newGamepad._isConnected = true;
  56961. }
  56962. else {
  56963. newGamepad = _this._addNewGamepad(gamepad);
  56964. }
  56965. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  56966. _this._startMonitoringGamepads();
  56967. };
  56968. this._onGamepadDisconnectedEvent = function (evt) {
  56969. var gamepad = evt.gamepad;
  56970. // Remove the gamepad from the list of gamepads to monitor.
  56971. for (var i in _this._babylonGamepads) {
  56972. if (_this._babylonGamepads[i].index === gamepad.index) {
  56973. var disconnectedGamepad = _this._babylonGamepads[i];
  56974. disconnectedGamepad._isConnected = false;
  56975. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  56976. break;
  56977. }
  56978. }
  56979. };
  56980. if (this._gamepadSupport) {
  56981. //first add already-connected gamepads
  56982. this._updateGamepadObjects();
  56983. if (this._babylonGamepads.length) {
  56984. this._startMonitoringGamepads();
  56985. }
  56986. // Checking if the gamepad connected event is supported (like in Firefox)
  56987. if (this._gamepadEventSupported) {
  56988. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  56989. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  56990. }
  56991. else {
  56992. this._startMonitoringGamepads();
  56993. }
  56994. }
  56995. }
  56996. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  56997. get: function () {
  56998. return this._babylonGamepads;
  56999. },
  57000. enumerable: true,
  57001. configurable: true
  57002. });
  57003. GamepadManager.prototype.getGamepadByType = function (type) {
  57004. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  57005. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  57006. var gamepad = _a[_i];
  57007. if (gamepad && gamepad.type === type) {
  57008. return gamepad;
  57009. }
  57010. }
  57011. return null;
  57012. };
  57013. GamepadManager.prototype.dispose = function () {
  57014. if (this._gamepadEventSupported) {
  57015. if (this._onGamepadConnectedEvent) {
  57016. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  57017. }
  57018. if (this._onGamepadDisconnectedEvent) {
  57019. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  57020. }
  57021. this._onGamepadConnectedEvent = null;
  57022. this._onGamepadDisconnectedEvent = null;
  57023. }
  57024. this._babylonGamepads.forEach(function (gamepad) {
  57025. gamepad.dispose();
  57026. });
  57027. this.onGamepadConnectedObservable.clear();
  57028. this.onGamepadDisconnectedObservable.clear();
  57029. this._oneGamepadConnected = false;
  57030. this._stopMonitoringGamepads();
  57031. this._babylonGamepads = [];
  57032. };
  57033. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  57034. if (!this._oneGamepadConnected) {
  57035. this._oneGamepadConnected = true;
  57036. }
  57037. var newGamepad;
  57038. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  57039. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  57040. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  57041. }
  57042. else if (gamepad.pose) {
  57043. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  57044. }
  57045. else {
  57046. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  57047. }
  57048. this._babylonGamepads[newGamepad.index] = newGamepad;
  57049. return newGamepad;
  57050. };
  57051. GamepadManager.prototype._startMonitoringGamepads = function () {
  57052. if (!this._isMonitoring) {
  57053. this._isMonitoring = true;
  57054. //back-comp
  57055. if (!this._scene) {
  57056. this._checkGamepadsStatus();
  57057. }
  57058. }
  57059. };
  57060. GamepadManager.prototype._stopMonitoringGamepads = function () {
  57061. this._isMonitoring = false;
  57062. };
  57063. GamepadManager.prototype._checkGamepadsStatus = function () {
  57064. var _this = this;
  57065. // Hack to be compatible Chrome
  57066. this._updateGamepadObjects();
  57067. for (var i in this._babylonGamepads) {
  57068. var gamepad = this._babylonGamepads[i];
  57069. if (!gamepad || !gamepad.isConnected) {
  57070. continue;
  57071. }
  57072. gamepad.update();
  57073. }
  57074. if (this._isMonitoring && !this._scene) {
  57075. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  57076. }
  57077. };
  57078. // This function is called only on Chrome, which does not properly support
  57079. // connection/disconnection events and forces you to recopy again the gamepad object
  57080. GamepadManager.prototype._updateGamepadObjects = function () {
  57081. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  57082. for (var i = 0; i < gamepads.length; i++) {
  57083. if (gamepads[i]) {
  57084. if (!this._babylonGamepads[gamepads[i].index]) {
  57085. var newGamepad = this._addNewGamepad(gamepads[i]);
  57086. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  57087. }
  57088. else {
  57089. // Forced to copy again this object for Chrome for unknown reason
  57090. this._babylonGamepads[i].browserGamepad = gamepads[i];
  57091. if (!this._babylonGamepads[i].isConnected) {
  57092. this._babylonGamepads[i]._isConnected = true;
  57093. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  57094. }
  57095. }
  57096. }
  57097. }
  57098. };
  57099. return GamepadManager;
  57100. }());
  57101. BABYLON.GamepadManager = GamepadManager;
  57102. })(BABYLON || (BABYLON = {}));
  57103. //# sourceMappingURL=babylon.gamepadManager.js.map
  57104. var BABYLON;
  57105. (function (BABYLON) {
  57106. var StickValues = /** @class */ (function () {
  57107. function StickValues(x, y) {
  57108. this.x = x;
  57109. this.y = y;
  57110. }
  57111. return StickValues;
  57112. }());
  57113. BABYLON.StickValues = StickValues;
  57114. var Gamepad = /** @class */ (function () {
  57115. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  57116. if (leftStickX === void 0) { leftStickX = 0; }
  57117. if (leftStickY === void 0) { leftStickY = 1; }
  57118. if (rightStickX === void 0) { rightStickX = 2; }
  57119. if (rightStickY === void 0) { rightStickY = 3; }
  57120. this.id = id;
  57121. this.index = index;
  57122. this.browserGamepad = browserGamepad;
  57123. this._isConnected = true;
  57124. this._invertLeftStickY = false;
  57125. this.type = Gamepad.GAMEPAD;
  57126. this._leftStickAxisX = leftStickX;
  57127. this._leftStickAxisY = leftStickY;
  57128. this._rightStickAxisX = rightStickX;
  57129. this._rightStickAxisY = rightStickY;
  57130. if (this.browserGamepad.axes.length >= 2) {
  57131. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  57132. }
  57133. if (this.browserGamepad.axes.length >= 4) {
  57134. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  57135. }
  57136. }
  57137. Object.defineProperty(Gamepad.prototype, "isConnected", {
  57138. get: function () {
  57139. return this._isConnected;
  57140. },
  57141. enumerable: true,
  57142. configurable: true
  57143. });
  57144. Gamepad.prototype.onleftstickchanged = function (callback) {
  57145. this._onleftstickchanged = callback;
  57146. };
  57147. Gamepad.prototype.onrightstickchanged = function (callback) {
  57148. this._onrightstickchanged = callback;
  57149. };
  57150. Object.defineProperty(Gamepad.prototype, "leftStick", {
  57151. get: function () {
  57152. return this._leftStick;
  57153. },
  57154. set: function (newValues) {
  57155. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  57156. this._onleftstickchanged(newValues);
  57157. }
  57158. this._leftStick = newValues;
  57159. },
  57160. enumerable: true,
  57161. configurable: true
  57162. });
  57163. Object.defineProperty(Gamepad.prototype, "rightStick", {
  57164. get: function () {
  57165. return this._rightStick;
  57166. },
  57167. set: function (newValues) {
  57168. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  57169. this._onrightstickchanged(newValues);
  57170. }
  57171. this._rightStick = newValues;
  57172. },
  57173. enumerable: true,
  57174. configurable: true
  57175. });
  57176. Gamepad.prototype.update = function () {
  57177. if (this._leftStick) {
  57178. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  57179. if (this._invertLeftStickY) {
  57180. this.leftStick.y *= -1;
  57181. }
  57182. }
  57183. if (this._rightStick) {
  57184. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  57185. }
  57186. };
  57187. Gamepad.prototype.dispose = function () {
  57188. };
  57189. Gamepad.GAMEPAD = 0;
  57190. Gamepad.GENERIC = 1;
  57191. Gamepad.XBOX = 2;
  57192. Gamepad.POSE_ENABLED = 3;
  57193. return Gamepad;
  57194. }());
  57195. BABYLON.Gamepad = Gamepad;
  57196. var GenericPad = /** @class */ (function (_super) {
  57197. __extends(GenericPad, _super);
  57198. function GenericPad(id, index, browserGamepad) {
  57199. var _this = _super.call(this, id, index, browserGamepad) || this;
  57200. _this.onButtonDownObservable = new BABYLON.Observable();
  57201. _this.onButtonUpObservable = new BABYLON.Observable();
  57202. _this.type = Gamepad.GENERIC;
  57203. _this._buttons = new Array(browserGamepad.buttons.length);
  57204. return _this;
  57205. }
  57206. GenericPad.prototype.onbuttondown = function (callback) {
  57207. this._onbuttondown = callback;
  57208. };
  57209. GenericPad.prototype.onbuttonup = function (callback) {
  57210. this._onbuttonup = callback;
  57211. };
  57212. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  57213. if (newValue !== currentValue) {
  57214. if (newValue === 1) {
  57215. if (this._onbuttondown) {
  57216. this._onbuttondown(buttonIndex);
  57217. }
  57218. this.onButtonDownObservable.notifyObservers(buttonIndex);
  57219. }
  57220. if (newValue === 0) {
  57221. if (this._onbuttonup) {
  57222. this._onbuttonup(buttonIndex);
  57223. }
  57224. this.onButtonUpObservable.notifyObservers(buttonIndex);
  57225. }
  57226. }
  57227. return newValue;
  57228. };
  57229. GenericPad.prototype.update = function () {
  57230. _super.prototype.update.call(this);
  57231. for (var index = 0; index < this._buttons.length; index++) {
  57232. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  57233. }
  57234. };
  57235. GenericPad.prototype.dispose = function () {
  57236. _super.prototype.dispose.call(this);
  57237. this.onButtonDownObservable.clear();
  57238. this.onButtonUpObservable.clear();
  57239. };
  57240. return GenericPad;
  57241. }(Gamepad));
  57242. BABYLON.GenericPad = GenericPad;
  57243. })(BABYLON || (BABYLON = {}));
  57244. //# sourceMappingURL=babylon.gamepad.js.map
  57245. var BABYLON;
  57246. (function (BABYLON) {
  57247. var Xbox360Button;
  57248. (function (Xbox360Button) {
  57249. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  57250. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  57251. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  57252. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  57253. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  57254. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  57255. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  57256. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  57257. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  57258. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  57259. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  57260. var Xbox360Dpad;
  57261. (function (Xbox360Dpad) {
  57262. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  57263. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  57264. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  57265. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  57266. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  57267. var Xbox360Pad = /** @class */ (function (_super) {
  57268. __extends(Xbox360Pad, _super);
  57269. function Xbox360Pad(id, index, gamepad, xboxOne) {
  57270. if (xboxOne === void 0) { xboxOne = false; }
  57271. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  57272. _this._leftTrigger = 0;
  57273. _this._rightTrigger = 0;
  57274. _this.onButtonDownObservable = new BABYLON.Observable();
  57275. _this.onButtonUpObservable = new BABYLON.Observable();
  57276. _this.onPadDownObservable = new BABYLON.Observable();
  57277. _this.onPadUpObservable = new BABYLON.Observable();
  57278. _this._buttonA = 0;
  57279. _this._buttonB = 0;
  57280. _this._buttonX = 0;
  57281. _this._buttonY = 0;
  57282. _this._buttonBack = 0;
  57283. _this._buttonStart = 0;
  57284. _this._buttonLB = 0;
  57285. _this._buttonRB = 0;
  57286. _this._buttonLeftStick = 0;
  57287. _this._buttonRightStick = 0;
  57288. _this._dPadUp = 0;
  57289. _this._dPadDown = 0;
  57290. _this._dPadLeft = 0;
  57291. _this._dPadRight = 0;
  57292. _this._isXboxOnePad = false;
  57293. _this.type = BABYLON.Gamepad.XBOX;
  57294. _this._isXboxOnePad = xboxOne;
  57295. return _this;
  57296. }
  57297. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  57298. this._onlefttriggerchanged = callback;
  57299. };
  57300. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  57301. this._onrighttriggerchanged = callback;
  57302. };
  57303. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  57304. get: function () {
  57305. return this._leftTrigger;
  57306. },
  57307. set: function (newValue) {
  57308. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  57309. this._onlefttriggerchanged(newValue);
  57310. }
  57311. this._leftTrigger = newValue;
  57312. },
  57313. enumerable: true,
  57314. configurable: true
  57315. });
  57316. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  57317. get: function () {
  57318. return this._rightTrigger;
  57319. },
  57320. set: function (newValue) {
  57321. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  57322. this._onrighttriggerchanged(newValue);
  57323. }
  57324. this._rightTrigger = newValue;
  57325. },
  57326. enumerable: true,
  57327. configurable: true
  57328. });
  57329. Xbox360Pad.prototype.onbuttondown = function (callback) {
  57330. this._onbuttondown = callback;
  57331. };
  57332. Xbox360Pad.prototype.onbuttonup = function (callback) {
  57333. this._onbuttonup = callback;
  57334. };
  57335. Xbox360Pad.prototype.ondpaddown = function (callback) {
  57336. this._ondpaddown = callback;
  57337. };
  57338. Xbox360Pad.prototype.ondpadup = function (callback) {
  57339. this._ondpadup = callback;
  57340. };
  57341. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  57342. if (newValue !== currentValue) {
  57343. if (newValue === 1) {
  57344. if (this._onbuttondown) {
  57345. this._onbuttondown(buttonType);
  57346. }
  57347. this.onButtonDownObservable.notifyObservers(buttonType);
  57348. }
  57349. if (newValue === 0) {
  57350. if (this._onbuttonup) {
  57351. this._onbuttonup(buttonType);
  57352. }
  57353. this.onButtonUpObservable.notifyObservers(buttonType);
  57354. }
  57355. }
  57356. return newValue;
  57357. };
  57358. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  57359. if (newValue !== currentValue) {
  57360. if (newValue === 1) {
  57361. if (this._ondpaddown) {
  57362. this._ondpaddown(buttonType);
  57363. }
  57364. this.onPadDownObservable.notifyObservers(buttonType);
  57365. }
  57366. if (newValue === 0) {
  57367. if (this._ondpadup) {
  57368. this._ondpadup(buttonType);
  57369. }
  57370. this.onPadUpObservable.notifyObservers(buttonType);
  57371. }
  57372. }
  57373. return newValue;
  57374. };
  57375. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  57376. get: function () {
  57377. return this._buttonA;
  57378. },
  57379. set: function (value) {
  57380. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  57381. },
  57382. enumerable: true,
  57383. configurable: true
  57384. });
  57385. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  57386. get: function () {
  57387. return this._buttonB;
  57388. },
  57389. set: function (value) {
  57390. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  57391. },
  57392. enumerable: true,
  57393. configurable: true
  57394. });
  57395. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  57396. get: function () {
  57397. return this._buttonX;
  57398. },
  57399. set: function (value) {
  57400. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  57401. },
  57402. enumerable: true,
  57403. configurable: true
  57404. });
  57405. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  57406. get: function () {
  57407. return this._buttonY;
  57408. },
  57409. set: function (value) {
  57410. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  57411. },
  57412. enumerable: true,
  57413. configurable: true
  57414. });
  57415. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  57416. get: function () {
  57417. return this._buttonStart;
  57418. },
  57419. set: function (value) {
  57420. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  57421. },
  57422. enumerable: true,
  57423. configurable: true
  57424. });
  57425. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  57426. get: function () {
  57427. return this._buttonBack;
  57428. },
  57429. set: function (value) {
  57430. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  57431. },
  57432. enumerable: true,
  57433. configurable: true
  57434. });
  57435. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  57436. get: function () {
  57437. return this._buttonLB;
  57438. },
  57439. set: function (value) {
  57440. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  57441. },
  57442. enumerable: true,
  57443. configurable: true
  57444. });
  57445. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  57446. get: function () {
  57447. return this._buttonRB;
  57448. },
  57449. set: function (value) {
  57450. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  57451. },
  57452. enumerable: true,
  57453. configurable: true
  57454. });
  57455. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  57456. get: function () {
  57457. return this._buttonLeftStick;
  57458. },
  57459. set: function (value) {
  57460. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  57461. },
  57462. enumerable: true,
  57463. configurable: true
  57464. });
  57465. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  57466. get: function () {
  57467. return this._buttonRightStick;
  57468. },
  57469. set: function (value) {
  57470. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  57471. },
  57472. enumerable: true,
  57473. configurable: true
  57474. });
  57475. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  57476. get: function () {
  57477. return this._dPadUp;
  57478. },
  57479. set: function (value) {
  57480. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  57481. },
  57482. enumerable: true,
  57483. configurable: true
  57484. });
  57485. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  57486. get: function () {
  57487. return this._dPadDown;
  57488. },
  57489. set: function (value) {
  57490. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  57491. },
  57492. enumerable: true,
  57493. configurable: true
  57494. });
  57495. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  57496. get: function () {
  57497. return this._dPadLeft;
  57498. },
  57499. set: function (value) {
  57500. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  57501. },
  57502. enumerable: true,
  57503. configurable: true
  57504. });
  57505. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  57506. get: function () {
  57507. return this._dPadRight;
  57508. },
  57509. set: function (value) {
  57510. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  57511. },
  57512. enumerable: true,
  57513. configurable: true
  57514. });
  57515. Xbox360Pad.prototype.update = function () {
  57516. _super.prototype.update.call(this);
  57517. if (this._isXboxOnePad) {
  57518. this.buttonA = this.browserGamepad.buttons[0].value;
  57519. this.buttonB = this.browserGamepad.buttons[1].value;
  57520. this.buttonX = this.browserGamepad.buttons[2].value;
  57521. this.buttonY = this.browserGamepad.buttons[3].value;
  57522. this.buttonLB = this.browserGamepad.buttons[4].value;
  57523. this.buttonRB = this.browserGamepad.buttons[5].value;
  57524. this.leftTrigger = this.browserGamepad.axes[2];
  57525. this.rightTrigger = this.browserGamepad.axes[5];
  57526. this.buttonBack = this.browserGamepad.buttons[9].value;
  57527. this.buttonStart = this.browserGamepad.buttons[8].value;
  57528. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  57529. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  57530. this.dPadUp = this.browserGamepad.buttons[11].value;
  57531. this.dPadDown = this.browserGamepad.buttons[12].value;
  57532. this.dPadLeft = this.browserGamepad.buttons[13].value;
  57533. this.dPadRight = this.browserGamepad.buttons[14].value;
  57534. }
  57535. else {
  57536. this.buttonA = this.browserGamepad.buttons[0].value;
  57537. this.buttonB = this.browserGamepad.buttons[1].value;
  57538. this.buttonX = this.browserGamepad.buttons[2].value;
  57539. this.buttonY = this.browserGamepad.buttons[3].value;
  57540. this.buttonLB = this.browserGamepad.buttons[4].value;
  57541. this.buttonRB = this.browserGamepad.buttons[5].value;
  57542. this.leftTrigger = this.browserGamepad.buttons[6].value;
  57543. this.rightTrigger = this.browserGamepad.buttons[7].value;
  57544. this.buttonBack = this.browserGamepad.buttons[8].value;
  57545. this.buttonStart = this.browserGamepad.buttons[9].value;
  57546. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  57547. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  57548. this.dPadUp = this.browserGamepad.buttons[12].value;
  57549. this.dPadDown = this.browserGamepad.buttons[13].value;
  57550. this.dPadLeft = this.browserGamepad.buttons[14].value;
  57551. this.dPadRight = this.browserGamepad.buttons[15].value;
  57552. }
  57553. };
  57554. Xbox360Pad.prototype.dispose = function () {
  57555. _super.prototype.dispose.call(this);
  57556. this.onButtonDownObservable.clear();
  57557. this.onButtonUpObservable.clear();
  57558. this.onPadDownObservable.clear();
  57559. this.onPadUpObservable.clear();
  57560. };
  57561. return Xbox360Pad;
  57562. }(BABYLON.Gamepad));
  57563. BABYLON.Xbox360Pad = Xbox360Pad;
  57564. })(BABYLON || (BABYLON = {}));
  57565. //# sourceMappingURL=babylon.xboxGamepad.js.map
  57566. var BABYLON;
  57567. (function (BABYLON) {
  57568. var PoseEnabledControllerType;
  57569. (function (PoseEnabledControllerType) {
  57570. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  57571. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  57572. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  57573. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 3] = "GENERIC";
  57574. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  57575. var PoseEnabledControllerHelper = /** @class */ (function () {
  57576. function PoseEnabledControllerHelper() {
  57577. }
  57578. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  57579. // Oculus Touch
  57580. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  57581. return new BABYLON.OculusTouchController(vrGamepad);
  57582. }
  57583. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  57584. return new BABYLON.WindowsMotionController(vrGamepad);
  57585. }
  57586. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  57587. return new BABYLON.ViveController(vrGamepad);
  57588. }
  57589. else {
  57590. return new BABYLON.GenericController(vrGamepad);
  57591. }
  57592. };
  57593. return PoseEnabledControllerHelper;
  57594. }());
  57595. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  57596. var PoseEnabledController = /** @class */ (function (_super) {
  57597. __extends(PoseEnabledController, _super);
  57598. function PoseEnabledController(browserGamepad) {
  57599. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  57600. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  57601. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  57602. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  57603. // Represents device position and rotation in babylon space
  57604. _this.devicePosition = BABYLON.Vector3.Zero();
  57605. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  57606. _this.deviceScaleFactor = 1;
  57607. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  57608. _this._deviceToWorld = BABYLON.Matrix.Identity();
  57609. _this._workingMatrix = BABYLON.Matrix.Identity();
  57610. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  57611. _this.controllerType = PoseEnabledControllerType.GENERIC;
  57612. _this.position = BABYLON.Vector3.Zero();
  57613. _this.rotationQuaternion = new BABYLON.Quaternion();
  57614. _this._calculatedPosition = BABYLON.Vector3.Zero();
  57615. _this._calculatedRotation = new BABYLON.Quaternion();
  57616. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  57617. return _this;
  57618. }
  57619. PoseEnabledController.prototype.update = function () {
  57620. _super.prototype.update.call(this);
  57621. var pose = this.browserGamepad.pose;
  57622. this.updateFromDevice(pose);
  57623. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  57624. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  57625. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  57626. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  57627. if (this._mesh) {
  57628. this._mesh.position.copyFrom(this.devicePosition);
  57629. if (this._mesh.rotationQuaternion) {
  57630. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  57631. }
  57632. }
  57633. };
  57634. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  57635. if (poseData) {
  57636. this.rawPose = poseData;
  57637. if (poseData.position) {
  57638. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  57639. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  57640. this._deviceRoomPosition.z *= -1;
  57641. }
  57642. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  57643. this._calculatedPosition.addInPlace(this.position);
  57644. }
  57645. var pose = this.rawPose;
  57646. if (poseData.orientation && pose.orientation) {
  57647. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  57648. if (this._mesh) {
  57649. if (this._mesh.getScene().useRightHandedSystem) {
  57650. this._deviceRoomRotationQuaternion.z *= -1;
  57651. this._deviceRoomRotationQuaternion.w *= -1;
  57652. }
  57653. else {
  57654. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  57655. }
  57656. }
  57657. // if the camera is set, rotate to the camera's rotation
  57658. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  57659. }
  57660. }
  57661. };
  57662. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  57663. if (this._mesh) {
  57664. this._mesh.parent = null;
  57665. }
  57666. this._mesh = mesh;
  57667. if (this._poseControlledCamera) {
  57668. this._mesh.parent = this._poseControlledCamera;
  57669. }
  57670. if (!this._mesh.rotationQuaternion) {
  57671. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  57672. }
  57673. };
  57674. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  57675. this._poseControlledCamera = camera;
  57676. if (this._mesh) {
  57677. this._mesh.parent = this._poseControlledCamera;
  57678. }
  57679. };
  57680. PoseEnabledController.prototype.dispose = function () {
  57681. if (this._mesh) {
  57682. this._mesh.dispose();
  57683. }
  57684. this._mesh = null;
  57685. _super.prototype.dispose.call(this);
  57686. };
  57687. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  57688. get: function () {
  57689. return this._mesh;
  57690. },
  57691. enumerable: true,
  57692. configurable: true
  57693. });
  57694. PoseEnabledController.prototype.getForwardRay = function (length) {
  57695. if (length === void 0) { length = 100; }
  57696. if (!this.mesh) {
  57697. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  57698. }
  57699. var m = this.mesh.getWorldMatrix();
  57700. var origin = m.getTranslation();
  57701. var forward = new BABYLON.Vector3(0, 0, -1);
  57702. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  57703. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  57704. return new BABYLON.Ray(origin, direction, length);
  57705. };
  57706. return PoseEnabledController;
  57707. }(BABYLON.Gamepad));
  57708. BABYLON.PoseEnabledController = PoseEnabledController;
  57709. })(BABYLON || (BABYLON = {}));
  57710. //# sourceMappingURL=babylon.poseEnabledController.js.map
  57711. var BABYLON;
  57712. (function (BABYLON) {
  57713. var WebVRController = /** @class */ (function (_super) {
  57714. __extends(WebVRController, _super);
  57715. function WebVRController(vrGamepad) {
  57716. var _this = _super.call(this, vrGamepad) || this;
  57717. // Observables
  57718. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  57719. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  57720. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  57721. _this.onPadStateChangedObservable = new BABYLON.Observable();
  57722. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  57723. _this.pad = { x: 0, y: 0 };
  57724. // avoid GC, store state in a tmp object
  57725. _this._changes = {
  57726. pressChanged: false,
  57727. touchChanged: false,
  57728. valueChanged: false,
  57729. changed: false
  57730. };
  57731. _this._buttons = new Array(vrGamepad.buttons.length);
  57732. _this.hand = vrGamepad.hand;
  57733. return _this;
  57734. }
  57735. WebVRController.prototype.onButtonStateChange = function (callback) {
  57736. this._onButtonStateChange = callback;
  57737. };
  57738. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  57739. get: function () {
  57740. return this._defaultModel;
  57741. },
  57742. enumerable: true,
  57743. configurable: true
  57744. });
  57745. WebVRController.prototype.update = function () {
  57746. _super.prototype.update.call(this);
  57747. for (var index = 0; index < this._buttons.length; index++) {
  57748. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  57749. }
  57750. ;
  57751. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  57752. this.pad.x = this.leftStick.x;
  57753. this.pad.y = this.leftStick.y;
  57754. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  57755. }
  57756. };
  57757. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  57758. if (!newState) {
  57759. newState = {
  57760. pressed: false,
  57761. touched: false,
  57762. value: 0
  57763. };
  57764. }
  57765. if (!currentState) {
  57766. this._buttons[buttonIndex] = {
  57767. pressed: newState.pressed,
  57768. touched: newState.touched,
  57769. value: newState.value
  57770. };
  57771. return;
  57772. }
  57773. this._checkChanges(newState, currentState);
  57774. if (this._changes.changed) {
  57775. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  57776. this.handleButtonChange(buttonIndex, newState, this._changes);
  57777. }
  57778. this._buttons[buttonIndex].pressed = newState.pressed;
  57779. this._buttons[buttonIndex].touched = newState.touched;
  57780. // oculus triggers are never 0, thou not touched.
  57781. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  57782. };
  57783. WebVRController.prototype._checkChanges = function (newState, currentState) {
  57784. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  57785. this._changes.touchChanged = newState.touched !== currentState.touched;
  57786. this._changes.valueChanged = newState.value !== currentState.value;
  57787. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  57788. return this._changes;
  57789. };
  57790. WebVRController.prototype.dispose = function () {
  57791. _super.prototype.dispose.call(this);
  57792. this.onTriggerStateChangedObservable.clear();
  57793. this.onMainButtonStateChangedObservable.clear();
  57794. this.onSecondaryButtonStateChangedObservable.clear();
  57795. this.onPadStateChangedObservable.clear();
  57796. this.onPadValuesChangedObservable.clear();
  57797. };
  57798. return WebVRController;
  57799. }(BABYLON.PoseEnabledController));
  57800. BABYLON.WebVRController = WebVRController;
  57801. })(BABYLON || (BABYLON = {}));
  57802. //# sourceMappingURL=babylon.webVRController.js.map
  57803. var BABYLON;
  57804. (function (BABYLON) {
  57805. var OculusTouchController = /** @class */ (function (_super) {
  57806. __extends(OculusTouchController, _super);
  57807. function OculusTouchController(vrGamepad) {
  57808. var _this = _super.call(this, vrGamepad) || this;
  57809. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  57810. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  57811. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  57812. return _this;
  57813. }
  57814. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  57815. var _this = this;
  57816. var meshName;
  57817. // Hand
  57818. if (this.hand === 'left') {
  57819. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  57820. }
  57821. else {
  57822. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  57823. }
  57824. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  57825. /*
  57826. Parent Mesh name: oculus_touch_left
  57827. - body
  57828. - trigger
  57829. - thumbstick
  57830. - grip
  57831. - button_y
  57832. - button_x
  57833. - button_enter
  57834. */
  57835. _this._defaultModel = newMeshes[1];
  57836. _this.attachToMesh(_this._defaultModel);
  57837. if (meshLoaded) {
  57838. meshLoaded(_this._defaultModel);
  57839. }
  57840. });
  57841. };
  57842. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  57843. // helper getters for left and right hand.
  57844. get: function () {
  57845. if (this.hand === 'right') {
  57846. return this.onMainButtonStateChangedObservable;
  57847. }
  57848. else {
  57849. throw new Error('No A button on left hand');
  57850. }
  57851. },
  57852. enumerable: true,
  57853. configurable: true
  57854. });
  57855. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  57856. get: function () {
  57857. if (this.hand === 'right') {
  57858. return this.onSecondaryButtonStateChangedObservable;
  57859. }
  57860. else {
  57861. throw new Error('No B button on left hand');
  57862. }
  57863. },
  57864. enumerable: true,
  57865. configurable: true
  57866. });
  57867. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  57868. get: function () {
  57869. if (this.hand === 'left') {
  57870. return this.onMainButtonStateChangedObservable;
  57871. }
  57872. else {
  57873. throw new Error('No X button on right hand');
  57874. }
  57875. },
  57876. enumerable: true,
  57877. configurable: true
  57878. });
  57879. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  57880. get: function () {
  57881. if (this.hand === 'left') {
  57882. return this.onSecondaryButtonStateChangedObservable;
  57883. }
  57884. else {
  57885. throw new Error('No Y button on right hand');
  57886. }
  57887. },
  57888. enumerable: true,
  57889. configurable: true
  57890. });
  57891. /*
  57892. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  57893. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  57894. 2) secondary trigger (same)
  57895. 3) A (right) X (left), touch, pressed = value
  57896. 4) B / Y
  57897. 5) thumb rest
  57898. */
  57899. OculusTouchController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  57900. var notifyObject = state; //{ state: state, changes: changes };
  57901. var triggerDirection = this.hand === 'right' ? -1 : 1;
  57902. switch (buttonIdx) {
  57903. case 0:
  57904. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  57905. return;
  57906. case 1:// index trigger
  57907. if (this._defaultModel) {
  57908. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  57909. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  57910. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  57911. }
  57912. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  57913. return;
  57914. case 2:// secondary trigger
  57915. if (this._defaultModel) {
  57916. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  57917. }
  57918. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  57919. return;
  57920. case 3:
  57921. if (this._defaultModel) {
  57922. if (notifyObject.pressed) {
  57923. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  57924. }
  57925. else {
  57926. (this._defaultModel.getChildren()[1]).position.y = 0;
  57927. }
  57928. }
  57929. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  57930. return;
  57931. case 4:
  57932. if (this._defaultModel) {
  57933. if (notifyObject.pressed) {
  57934. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  57935. }
  57936. else {
  57937. (this._defaultModel.getChildren()[2]).position.y = 0;
  57938. }
  57939. }
  57940. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  57941. return;
  57942. case 5:
  57943. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  57944. return;
  57945. }
  57946. };
  57947. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  57948. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  57949. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  57950. return OculusTouchController;
  57951. }(BABYLON.WebVRController));
  57952. BABYLON.OculusTouchController = OculusTouchController;
  57953. })(BABYLON || (BABYLON = {}));
  57954. //# sourceMappingURL=babylon.oculusTouchController.js.map
  57955. var BABYLON;
  57956. (function (BABYLON) {
  57957. var ViveController = /** @class */ (function (_super) {
  57958. __extends(ViveController, _super);
  57959. function ViveController(vrGamepad) {
  57960. var _this = _super.call(this, vrGamepad) || this;
  57961. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  57962. _this._invertLeftStickY = true;
  57963. return _this;
  57964. }
  57965. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  57966. var _this = this;
  57967. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  57968. /*
  57969. Parent Mesh name: ViveWand
  57970. - body
  57971. - r_gripper
  57972. - l_gripper
  57973. - menu_button
  57974. - system_button
  57975. - trackpad
  57976. - trigger
  57977. - LED
  57978. */
  57979. _this._defaultModel = newMeshes[1];
  57980. _this.attachToMesh(_this._defaultModel);
  57981. if (meshLoaded) {
  57982. meshLoaded(_this._defaultModel);
  57983. }
  57984. });
  57985. };
  57986. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  57987. get: function () {
  57988. return this.onMainButtonStateChangedObservable;
  57989. },
  57990. enumerable: true,
  57991. configurable: true
  57992. });
  57993. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  57994. get: function () {
  57995. return this.onMainButtonStateChangedObservable;
  57996. },
  57997. enumerable: true,
  57998. configurable: true
  57999. });
  58000. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  58001. get: function () {
  58002. return this.onSecondaryButtonStateChangedObservable;
  58003. },
  58004. enumerable: true,
  58005. configurable: true
  58006. });
  58007. /**
  58008. * Vive mapping:
  58009. * 0: touchpad
  58010. * 1: trigger
  58011. * 2: left AND right buttons
  58012. * 3: menu button
  58013. */
  58014. ViveController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  58015. var notifyObject = state; //{ state: state, changes: changes };
  58016. switch (buttonIdx) {
  58017. case 0:
  58018. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  58019. return;
  58020. case 1:// index trigger
  58021. if (this._defaultModel) {
  58022. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  58023. }
  58024. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  58025. return;
  58026. case 2:// left AND right button
  58027. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  58028. return;
  58029. case 3:
  58030. if (this._defaultModel) {
  58031. if (notifyObject.pressed) {
  58032. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  58033. }
  58034. else {
  58035. (this._defaultModel.getChildren()[2]).position.y = 0;
  58036. }
  58037. }
  58038. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  58039. return;
  58040. }
  58041. };
  58042. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  58043. ViveController.MODEL_FILENAME = 'wand.babylon';
  58044. return ViveController;
  58045. }(BABYLON.WebVRController));
  58046. BABYLON.ViveController = ViveController;
  58047. })(BABYLON || (BABYLON = {}));
  58048. //# sourceMappingURL=babylon.viveController.js.map
  58049. var BABYLON;
  58050. (function (BABYLON) {
  58051. var GenericController = /** @class */ (function (_super) {
  58052. __extends(GenericController, _super);
  58053. function GenericController(vrGamepad) {
  58054. return _super.call(this, vrGamepad) || this;
  58055. }
  58056. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  58057. var _this = this;
  58058. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  58059. _this._defaultModel = newMeshes[1];
  58060. _this.attachToMesh(_this._defaultModel);
  58061. if (meshLoaded) {
  58062. meshLoaded(_this._defaultModel);
  58063. }
  58064. });
  58065. };
  58066. GenericController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  58067. console.log("Button id: " + buttonIdx + "state: ");
  58068. console.dir(state);
  58069. };
  58070. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  58071. GenericController.MODEL_FILENAME = 'generic.babylon';
  58072. return GenericController;
  58073. }(BABYLON.WebVRController));
  58074. BABYLON.GenericController = GenericController;
  58075. })(BABYLON || (BABYLON = {}));
  58076. //# sourceMappingURL=babylon.genericController.js.map
  58077. var BABYLON;
  58078. (function (BABYLON) {
  58079. var LoadedMeshInfo = /** @class */ (function () {
  58080. function LoadedMeshInfo() {
  58081. this.buttonMeshes = {};
  58082. this.axisMeshes = {};
  58083. }
  58084. return LoadedMeshInfo;
  58085. }());
  58086. var WindowsMotionController = /** @class */ (function (_super) {
  58087. __extends(WindowsMotionController, _super);
  58088. function WindowsMotionController(vrGamepad) {
  58089. var _this = _super.call(this, vrGamepad) || this;
  58090. _this._mapping = {
  58091. // Semantic button names
  58092. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  58093. // A mapping of the button name to glTF model node name
  58094. // that should be transformed by button value.
  58095. buttonMeshNames: {
  58096. 'trigger': 'SELECT',
  58097. 'menu': 'MENU',
  58098. 'grip': 'GRASP',
  58099. 'thumbstick': 'THUMBSTICK_PRESS',
  58100. 'trackpad': 'TOUCHPAD_PRESS'
  58101. },
  58102. // This mapping is used to translate from the Motion Controller to Babylon semantics
  58103. buttonObservableNames: {
  58104. 'trigger': 'onTriggerStateChangedObservable',
  58105. 'menu': 'onSecondaryButtonStateChangedObservable',
  58106. 'grip': 'onMainButtonStateChangedObservable',
  58107. 'thumbstick': 'onPadStateChangedObservable',
  58108. 'trackpad': 'onTrackpadChangedObservable'
  58109. },
  58110. // A mapping of the axis name to glTF model node name
  58111. // that should be transformed by axis value.
  58112. // This array mirrors the browserGamepad.axes array, such that
  58113. // the mesh corresponding to axis 0 is in this array index 0.
  58114. axisMeshNames: [
  58115. 'THUMBSTICK_X',
  58116. 'THUMBSTICK_Y',
  58117. 'TOUCHPAD_TOUCH_X',
  58118. 'TOUCHPAD_TOUCH_Y'
  58119. ],
  58120. pointingPoseMeshName: 'POINTING_POSE'
  58121. };
  58122. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  58123. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  58124. _this.trackpad = { x: 0, y: 0 };
  58125. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  58126. _this._loadedMeshInfo = null;
  58127. return _this;
  58128. }
  58129. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  58130. get: function () {
  58131. return this.onTriggerStateChangedObservable;
  58132. },
  58133. enumerable: true,
  58134. configurable: true
  58135. });
  58136. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  58137. get: function () {
  58138. return this.onSecondaryButtonStateChangedObservable;
  58139. },
  58140. enumerable: true,
  58141. configurable: true
  58142. });
  58143. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  58144. get: function () {
  58145. return this.onMainButtonStateChangedObservable;
  58146. },
  58147. enumerable: true,
  58148. configurable: true
  58149. });
  58150. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  58151. get: function () {
  58152. return this.onPadStateChangedObservable;
  58153. },
  58154. enumerable: true,
  58155. configurable: true
  58156. });
  58157. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  58158. get: function () {
  58159. return this.onTrackpadChangedObservable;
  58160. },
  58161. enumerable: true,
  58162. configurable: true
  58163. });
  58164. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  58165. get: function () {
  58166. return this.onTrackpadValuesChangedObservable;
  58167. },
  58168. enumerable: true,
  58169. configurable: true
  58170. });
  58171. /**
  58172. * Called once per frame by the engine.
  58173. */
  58174. WindowsMotionController.prototype.update = function () {
  58175. _super.prototype.update.call(this);
  58176. // Only need to animate axes if there is a loaded mesh
  58177. if (this._loadedMeshInfo) {
  58178. if (this.browserGamepad.axes) {
  58179. if (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y) {
  58180. this.trackpad.x = this.browserGamepad["axes"][2];
  58181. this.trackpad.y = this.browserGamepad["axes"][3];
  58182. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  58183. }
  58184. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  58185. this.lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  58186. }
  58187. }
  58188. }
  58189. };
  58190. /**
  58191. * Called once for each button that changed state since the last frame
  58192. * @param buttonIdx Which button index changed
  58193. * @param state New state of the button
  58194. * @param changes Which properties on the state changed since last frame
  58195. */
  58196. WindowsMotionController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  58197. var buttonName = this._mapping.buttons[buttonIdx];
  58198. if (!buttonName) {
  58199. return;
  58200. }
  58201. // Only emit events for buttons that we know how to map from index to name
  58202. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  58203. if (observable) {
  58204. observable.notifyObservers(state);
  58205. }
  58206. this.lerpButtonTransform(buttonName, state.value);
  58207. };
  58208. WindowsMotionController.prototype.lerpButtonTransform = function (buttonName, buttonValue) {
  58209. // If there is no loaded mesh, there is nothing to transform.
  58210. if (!this._loadedMeshInfo) {
  58211. return;
  58212. }
  58213. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  58214. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  58215. return;
  58216. }
  58217. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  58218. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  58219. };
  58220. WindowsMotionController.prototype.lerpAxisTransform = function (axis, axisValue) {
  58221. if (!this._loadedMeshInfo) {
  58222. return;
  58223. }
  58224. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  58225. if (!meshInfo) {
  58226. return;
  58227. }
  58228. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  58229. return;
  58230. }
  58231. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  58232. var lerpValue = axisValue * 0.5 + 0.5;
  58233. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  58234. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  58235. };
  58236. /**
  58237. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  58238. * @param scene scene in which to add meshes
  58239. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  58240. */
  58241. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  58242. var _this = this;
  58243. if (forceDefault === void 0) { forceDefault = false; }
  58244. var path;
  58245. var filename;
  58246. // Checking if GLB loader is present
  58247. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  58248. // Determine the device specific folder based on the ID suffix
  58249. var device = 'default';
  58250. if (this.id && !forceDefault) {
  58251. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  58252. device = ((match && match[0]) || device);
  58253. }
  58254. // Hand
  58255. if (this.hand === 'left') {
  58256. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  58257. }
  58258. else {
  58259. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  58260. }
  58261. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  58262. }
  58263. else {
  58264. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  58265. path = BABYLON.GenericController.MODEL_BASE_URL;
  58266. filename = BABYLON.GenericController.MODEL_FILENAME;
  58267. }
  58268. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  58269. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  58270. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  58271. if (!_this._loadedMeshInfo) {
  58272. return;
  58273. }
  58274. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  58275. _this.attachToMesh(_this._defaultModel);
  58276. if (meshLoaded) {
  58277. meshLoaded(_this._defaultModel);
  58278. }
  58279. }, null, function (scene, message) {
  58280. BABYLON.Tools.Log(message);
  58281. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  58282. if (!forceDefault) {
  58283. _this.initControllerMesh(scene, meshLoaded, true);
  58284. }
  58285. });
  58286. };
  58287. /**
  58288. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  58289. * can be transformed by button presses and axes values, based on this._mapping.
  58290. *
  58291. * @param scene scene in which the meshes exist
  58292. * @param meshes list of meshes that make up the controller model to process
  58293. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  58294. */
  58295. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  58296. var loadedMeshInfo = null;
  58297. // Create a new mesh to contain the glTF hierarchy
  58298. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  58299. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  58300. var childMesh = null;
  58301. for (var i = 0; i < meshes.length; i++) {
  58302. var mesh = meshes[i];
  58303. if (!mesh.parent) {
  58304. // Exclude controller meshes from picking results
  58305. mesh.isPickable = false;
  58306. // Handle root node, attach to the new parentMesh
  58307. childMesh = mesh;
  58308. break;
  58309. }
  58310. }
  58311. if (childMesh) {
  58312. childMesh.setParent(parentMesh);
  58313. // Create our mesh info. Note that this method will always return non-null.
  58314. loadedMeshInfo = this.createMeshInfo(parentMesh);
  58315. }
  58316. else {
  58317. BABYLON.Tools.Warn('Could not find root node in model file.');
  58318. }
  58319. return loadedMeshInfo;
  58320. };
  58321. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  58322. var loadedMeshInfo = new LoadedMeshInfo();
  58323. var i;
  58324. loadedMeshInfo.rootNode = rootNode;
  58325. // Reset the caches
  58326. loadedMeshInfo.buttonMeshes = {};
  58327. loadedMeshInfo.axisMeshes = {};
  58328. // Button Meshes
  58329. for (i = 0; i < this._mapping.buttons.length; i++) {
  58330. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  58331. if (!buttonMeshName) {
  58332. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  58333. continue;
  58334. }
  58335. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  58336. if (!buttonMesh) {
  58337. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  58338. continue;
  58339. }
  58340. var buttonMeshInfo = {
  58341. index: i,
  58342. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  58343. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  58344. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  58345. };
  58346. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  58347. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  58348. }
  58349. else {
  58350. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  58351. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  58352. '(VALUE: ' + !!buttonMeshInfo.value +
  58353. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  58354. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  58355. ')');
  58356. }
  58357. }
  58358. // Axis Meshes
  58359. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  58360. var axisMeshName = this._mapping.axisMeshNames[i];
  58361. if (!axisMeshName) {
  58362. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  58363. continue;
  58364. }
  58365. var axisMesh = getChildByName(rootNode, axisMeshName);
  58366. if (!axisMesh) {
  58367. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  58368. continue;
  58369. }
  58370. var axisMeshInfo = {
  58371. index: i,
  58372. value: getImmediateChildByName(axisMesh, 'VALUE'),
  58373. min: getImmediateChildByName(axisMesh, 'MIN'),
  58374. max: getImmediateChildByName(axisMesh, 'MAX')
  58375. };
  58376. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  58377. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  58378. }
  58379. else {
  58380. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  58381. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  58382. '(VALUE: ' + !!axisMeshInfo.value +
  58383. ', MIN: ' + !!axisMeshInfo.min +
  58384. ', MAX:' + !!axisMeshInfo.max +
  58385. ')');
  58386. }
  58387. }
  58388. // Pointing Ray
  58389. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  58390. if (!loadedMeshInfo.pointingPoseNode) {
  58391. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  58392. }
  58393. return loadedMeshInfo;
  58394. // Look through all children recursively. This will return null if no mesh exists with the given name.
  58395. function getChildByName(node, name) {
  58396. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  58397. }
  58398. // Look through only immediate children. This will return null if no mesh exists with the given name.
  58399. function getImmediateChildByName(node, name) {
  58400. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  58401. }
  58402. };
  58403. WindowsMotionController.prototype.getForwardRay = function (length) {
  58404. if (length === void 0) { length = 100; }
  58405. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  58406. return _super.prototype.getForwardRay.call(this, length);
  58407. }
  58408. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  58409. var origin = m.getTranslation();
  58410. var forward = new BABYLON.Vector3(0, 0, -1);
  58411. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  58412. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  58413. return new BABYLON.Ray(origin, direction, length);
  58414. };
  58415. WindowsMotionController.prototype.dispose = function () {
  58416. _super.prototype.dispose.call(this);
  58417. this.onTrackpadChangedObservable.clear();
  58418. };
  58419. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  58420. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  58421. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  58422. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  58423. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  58424. return WindowsMotionController;
  58425. }(BABYLON.WebVRController));
  58426. BABYLON.WindowsMotionController = WindowsMotionController;
  58427. })(BABYLON || (BABYLON = {}));
  58428. //# sourceMappingURL=babylon.windowsMotionController.js.map
  58429. var BABYLON;
  58430. (function (BABYLON) {
  58431. var FollowCamera = /** @class */ (function (_super) {
  58432. __extends(FollowCamera, _super);
  58433. function FollowCamera(name, position, scene, lockedTarget) {
  58434. if (lockedTarget === void 0) { lockedTarget = null; }
  58435. var _this = _super.call(this, name, position, scene) || this;
  58436. _this.radius = 12;
  58437. _this.rotationOffset = 0;
  58438. _this.heightOffset = 4;
  58439. _this.cameraAcceleration = 0.05;
  58440. _this.maxCameraSpeed = 20;
  58441. _this.lockedTarget = lockedTarget;
  58442. return _this;
  58443. }
  58444. FollowCamera.prototype.getRadians = function (degrees) {
  58445. return degrees * Math.PI / 180;
  58446. };
  58447. FollowCamera.prototype.follow = function (cameraTarget) {
  58448. if (!cameraTarget)
  58449. return;
  58450. var yRotation;
  58451. if (cameraTarget.rotationQuaternion) {
  58452. var rotMatrix = new BABYLON.Matrix();
  58453. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  58454. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  58455. }
  58456. else {
  58457. yRotation = cameraTarget.rotation.y;
  58458. }
  58459. var radians = this.getRadians(this.rotationOffset) + yRotation;
  58460. var targetPosition = cameraTarget.getAbsolutePosition();
  58461. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  58462. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  58463. var dx = targetX - this.position.x;
  58464. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  58465. var dz = (targetZ) - this.position.z;
  58466. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  58467. var vy = dy * this.cameraAcceleration;
  58468. var vz = dz * this.cameraAcceleration * 2;
  58469. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  58470. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  58471. }
  58472. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  58473. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  58474. }
  58475. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  58476. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  58477. }
  58478. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  58479. this.setTarget(targetPosition);
  58480. };
  58481. FollowCamera.prototype._checkInputs = function () {
  58482. _super.prototype._checkInputs.call(this);
  58483. if (this.lockedTarget) {
  58484. this.follow(this.lockedTarget);
  58485. }
  58486. };
  58487. FollowCamera.prototype.getClassName = function () {
  58488. return "FollowCamera";
  58489. };
  58490. __decorate([
  58491. BABYLON.serialize()
  58492. ], FollowCamera.prototype, "radius", void 0);
  58493. __decorate([
  58494. BABYLON.serialize()
  58495. ], FollowCamera.prototype, "rotationOffset", void 0);
  58496. __decorate([
  58497. BABYLON.serialize()
  58498. ], FollowCamera.prototype, "heightOffset", void 0);
  58499. __decorate([
  58500. BABYLON.serialize()
  58501. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  58502. __decorate([
  58503. BABYLON.serialize()
  58504. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  58505. __decorate([
  58506. BABYLON.serializeAsMeshReference("lockedTargetId")
  58507. ], FollowCamera.prototype, "lockedTarget", void 0);
  58508. return FollowCamera;
  58509. }(BABYLON.TargetCamera));
  58510. BABYLON.FollowCamera = FollowCamera;
  58511. var ArcFollowCamera = /** @class */ (function (_super) {
  58512. __extends(ArcFollowCamera, _super);
  58513. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  58514. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  58515. _this.alpha = alpha;
  58516. _this.beta = beta;
  58517. _this.radius = radius;
  58518. _this.target = target;
  58519. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  58520. _this.follow();
  58521. return _this;
  58522. }
  58523. ArcFollowCamera.prototype.follow = function () {
  58524. if (!this.target) {
  58525. return;
  58526. }
  58527. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  58528. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  58529. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  58530. var targetPosition = this.target.getAbsolutePosition();
  58531. this.position = targetPosition.add(this._cartesianCoordinates);
  58532. this.setTarget(targetPosition);
  58533. };
  58534. ArcFollowCamera.prototype._checkInputs = function () {
  58535. _super.prototype._checkInputs.call(this);
  58536. this.follow();
  58537. };
  58538. ArcFollowCamera.prototype.getClassName = function () {
  58539. return "ArcFollowCamera";
  58540. };
  58541. return ArcFollowCamera;
  58542. }(BABYLON.TargetCamera));
  58543. BABYLON.ArcFollowCamera = ArcFollowCamera;
  58544. })(BABYLON || (BABYLON = {}));
  58545. //# sourceMappingURL=babylon.followCamera.js.map
  58546. var BABYLON;
  58547. (function (BABYLON) {
  58548. // We're mainly based on the logic defined into the FreeCamera code
  58549. var UniversalCamera = /** @class */ (function (_super) {
  58550. __extends(UniversalCamera, _super);
  58551. //-- end properties for backward compatibility for inputs
  58552. function UniversalCamera(name, position, scene) {
  58553. var _this = _super.call(this, name, position, scene) || this;
  58554. _this.inputs.addGamepad();
  58555. return _this;
  58556. }
  58557. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  58558. //-- Begin properties for backward compatibility for inputs
  58559. get: function () {
  58560. var gamepad = this.inputs.attached["gamepad"];
  58561. if (gamepad)
  58562. return gamepad.gamepadAngularSensibility;
  58563. return 0;
  58564. },
  58565. set: function (value) {
  58566. var gamepad = this.inputs.attached["gamepad"];
  58567. if (gamepad)
  58568. gamepad.gamepadAngularSensibility = value;
  58569. },
  58570. enumerable: true,
  58571. configurable: true
  58572. });
  58573. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  58574. get: function () {
  58575. var gamepad = this.inputs.attached["gamepad"];
  58576. if (gamepad)
  58577. return gamepad.gamepadMoveSensibility;
  58578. return 0;
  58579. },
  58580. set: function (value) {
  58581. var gamepad = this.inputs.attached["gamepad"];
  58582. if (gamepad)
  58583. gamepad.gamepadMoveSensibility = value;
  58584. },
  58585. enumerable: true,
  58586. configurable: true
  58587. });
  58588. UniversalCamera.prototype.getClassName = function () {
  58589. return "UniversalCamera";
  58590. };
  58591. return UniversalCamera;
  58592. }(BABYLON.TouchCamera));
  58593. BABYLON.UniversalCamera = UniversalCamera;
  58594. })(BABYLON || (BABYLON = {}));
  58595. //# sourceMappingURL=babylon.universalCamera.js.map
  58596. var BABYLON;
  58597. (function (BABYLON) {
  58598. // We're mainly based on the logic defined into the FreeCamera code
  58599. var GamepadCamera = /** @class */ (function (_super) {
  58600. __extends(GamepadCamera, _super);
  58601. //-- end properties for backward compatibility for inputs
  58602. function GamepadCamera(name, position, scene) {
  58603. return _super.call(this, name, position, scene) || this;
  58604. }
  58605. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  58606. //-- Begin properties for backward compatibility for inputs
  58607. get: function () {
  58608. var gamepad = this.inputs.attached["gamepad"];
  58609. if (gamepad)
  58610. return gamepad.gamepadAngularSensibility;
  58611. return 0;
  58612. },
  58613. set: function (value) {
  58614. var gamepad = this.inputs.attached["gamepad"];
  58615. if (gamepad)
  58616. gamepad.gamepadAngularSensibility = value;
  58617. },
  58618. enumerable: true,
  58619. configurable: true
  58620. });
  58621. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  58622. get: function () {
  58623. var gamepad = this.inputs.attached["gamepad"];
  58624. if (gamepad)
  58625. return gamepad.gamepadMoveSensibility;
  58626. return 0;
  58627. },
  58628. set: function (value) {
  58629. var gamepad = this.inputs.attached["gamepad"];
  58630. if (gamepad)
  58631. gamepad.gamepadMoveSensibility = value;
  58632. },
  58633. enumerable: true,
  58634. configurable: true
  58635. });
  58636. GamepadCamera.prototype.getClassName = function () {
  58637. return "GamepadCamera";
  58638. };
  58639. return GamepadCamera;
  58640. }(BABYLON.UniversalCamera));
  58641. BABYLON.GamepadCamera = GamepadCamera;
  58642. })(BABYLON || (BABYLON = {}));
  58643. //# sourceMappingURL=babylon.gamepadCamera.js.map
  58644. var BABYLON;
  58645. (function (BABYLON) {
  58646. var PostProcessRenderPipelineManager = /** @class */ (function () {
  58647. function PostProcessRenderPipelineManager() {
  58648. this._renderPipelines = {};
  58649. }
  58650. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  58651. this._renderPipelines[renderPipeline._name] = renderPipeline;
  58652. };
  58653. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  58654. if (unique === void 0) { unique = false; }
  58655. var renderPipeline = this._renderPipelines[renderPipelineName];
  58656. if (!renderPipeline) {
  58657. return;
  58658. }
  58659. renderPipeline._attachCameras(cameras, unique);
  58660. };
  58661. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  58662. var renderPipeline = this._renderPipelines[renderPipelineName];
  58663. if (!renderPipeline) {
  58664. return;
  58665. }
  58666. renderPipeline._detachCameras(cameras);
  58667. };
  58668. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  58669. var renderPipeline = this._renderPipelines[renderPipelineName];
  58670. if (!renderPipeline) {
  58671. return;
  58672. }
  58673. renderPipeline._enableEffect(renderEffectName, cameras);
  58674. };
  58675. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  58676. var renderPipeline = this._renderPipelines[renderPipelineName];
  58677. if (!renderPipeline) {
  58678. return;
  58679. }
  58680. renderPipeline._disableEffect(renderEffectName, cameras);
  58681. };
  58682. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  58683. var renderPipeline = this._renderPipelines[renderPipelineName];
  58684. if (!renderPipeline) {
  58685. return;
  58686. }
  58687. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  58688. };
  58689. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  58690. var renderPipeline = this._renderPipelines[renderPipelineName];
  58691. if (!renderPipeline) {
  58692. return;
  58693. }
  58694. renderPipeline._disableDisplayOnlyPass(cameras);
  58695. };
  58696. PostProcessRenderPipelineManager.prototype.update = function () {
  58697. for (var renderPipelineName in this._renderPipelines) {
  58698. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  58699. var pipeline = this._renderPipelines[renderPipelineName];
  58700. if (!pipeline.isSupported) {
  58701. pipeline.dispose();
  58702. delete this._renderPipelines[renderPipelineName];
  58703. }
  58704. else {
  58705. pipeline._update();
  58706. }
  58707. }
  58708. }
  58709. };
  58710. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  58711. for (var renderPipelineName in this._renderPipelines) {
  58712. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  58713. var pipeline = this._renderPipelines[renderPipelineName];
  58714. pipeline._rebuild();
  58715. }
  58716. }
  58717. };
  58718. PostProcessRenderPipelineManager.prototype.dispose = function () {
  58719. for (var renderPipelineName in this._renderPipelines) {
  58720. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  58721. var pipeline = this._renderPipelines[renderPipelineName];
  58722. pipeline.dispose();
  58723. }
  58724. }
  58725. };
  58726. return PostProcessRenderPipelineManager;
  58727. }());
  58728. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  58729. })(BABYLON || (BABYLON = {}));
  58730. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  58731. var BABYLON;
  58732. (function (BABYLON) {
  58733. var PostProcessRenderPass = /** @class */ (function () {
  58734. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  58735. this._refCount = 0;
  58736. this._name = name;
  58737. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  58738. this.setRenderList(renderList);
  58739. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  58740. this._renderTexture.onAfterRenderObservable.add(afterRender);
  58741. this._scene = scene;
  58742. this._renderList = renderList;
  58743. }
  58744. // private
  58745. PostProcessRenderPass.prototype._incRefCount = function () {
  58746. if (this._refCount === 0) {
  58747. this._scene.customRenderTargets.push(this._renderTexture);
  58748. }
  58749. return ++this._refCount;
  58750. };
  58751. PostProcessRenderPass.prototype._decRefCount = function () {
  58752. this._refCount--;
  58753. if (this._refCount <= 0) {
  58754. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  58755. }
  58756. return this._refCount;
  58757. };
  58758. PostProcessRenderPass.prototype._update = function () {
  58759. this.setRenderList(this._renderList);
  58760. };
  58761. // public
  58762. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  58763. this._renderTexture.renderList = renderList;
  58764. };
  58765. PostProcessRenderPass.prototype.getRenderTexture = function () {
  58766. return this._renderTexture;
  58767. };
  58768. return PostProcessRenderPass;
  58769. }());
  58770. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  58771. })(BABYLON || (BABYLON = {}));
  58772. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  58773. var BABYLON;
  58774. (function (BABYLON) {
  58775. var PostProcessRenderEffect = /** @class */ (function () {
  58776. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  58777. this._name = name;
  58778. this._singleInstance = singleInstance || true;
  58779. this._getPostProcess = getPostProcess;
  58780. this._cameras = {};
  58781. this._indicesForCamera = {};
  58782. this._postProcesses = {};
  58783. this._renderPasses = {};
  58784. this._renderEffectAsPasses = {};
  58785. }
  58786. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  58787. get: function () {
  58788. for (var index in this._postProcesses) {
  58789. if (!this._postProcesses[index].isSupported) {
  58790. return false;
  58791. }
  58792. }
  58793. return true;
  58794. },
  58795. enumerable: true,
  58796. configurable: true
  58797. });
  58798. PostProcessRenderEffect.prototype._update = function () {
  58799. for (var renderPassName in this._renderPasses) {
  58800. this._renderPasses[renderPassName]._update();
  58801. }
  58802. };
  58803. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  58804. this._renderPasses[renderPass._name] = renderPass;
  58805. this._linkParameters();
  58806. };
  58807. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  58808. delete this._renderPasses[renderPass._name];
  58809. this._linkParameters();
  58810. };
  58811. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  58812. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  58813. this._linkParameters();
  58814. };
  58815. PostProcessRenderEffect.prototype.getPass = function (passName) {
  58816. for (var renderPassName in this._renderPasses) {
  58817. if (renderPassName === passName) {
  58818. return this._renderPasses[passName];
  58819. }
  58820. }
  58821. return null;
  58822. };
  58823. PostProcessRenderEffect.prototype.emptyPasses = function () {
  58824. this._renderPasses = {};
  58825. this._linkParameters();
  58826. };
  58827. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  58828. var cameraKey;
  58829. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  58830. if (!cams) {
  58831. return;
  58832. }
  58833. for (var i = 0; i < cams.length; i++) {
  58834. var camera = cams[i];
  58835. var cameraName = camera.name;
  58836. if (this._singleInstance) {
  58837. cameraKey = 0;
  58838. }
  58839. else {
  58840. cameraKey = cameraName;
  58841. }
  58842. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  58843. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  58844. if (!this._indicesForCamera[cameraName]) {
  58845. this._indicesForCamera[cameraName] = [];
  58846. }
  58847. this._indicesForCamera[cameraName].push(index);
  58848. if (!this._cameras[cameraName]) {
  58849. this._cameras[cameraName] = camera;
  58850. }
  58851. for (var passName in this._renderPasses) {
  58852. this._renderPasses[passName]._incRefCount();
  58853. }
  58854. }
  58855. this._linkParameters();
  58856. };
  58857. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  58858. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  58859. if (!cams) {
  58860. return;
  58861. }
  58862. for (var i = 0; i < cams.length; i++) {
  58863. var camera = cams[i];
  58864. var cameraName = camera.name;
  58865. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName]);
  58866. if (this._cameras[cameraName]) {
  58867. //this._indicesForCamera.splice(index, 1);
  58868. this._cameras[cameraName] = null;
  58869. }
  58870. for (var passName in this._renderPasses) {
  58871. this._renderPasses[passName]._decRefCount();
  58872. }
  58873. }
  58874. };
  58875. PostProcessRenderEffect.prototype._enable = function (cameras) {
  58876. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  58877. if (!cams) {
  58878. return;
  58879. }
  58880. for (var i = 0; i < cams.length; i++) {
  58881. var camera = cams[i];
  58882. var cameraName = camera.name;
  58883. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  58884. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  58885. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  58886. }
  58887. }
  58888. for (var passName in this._renderPasses) {
  58889. this._renderPasses[passName]._incRefCount();
  58890. }
  58891. }
  58892. };
  58893. PostProcessRenderEffect.prototype._disable = function (cameras) {
  58894. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  58895. if (!cams) {
  58896. return;
  58897. }
  58898. for (var i = 0; i < cams.length; i++) {
  58899. var camera = cams[i];
  58900. var cameraName = camera.Name;
  58901. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName]);
  58902. for (var passName in this._renderPasses) {
  58903. this._renderPasses[passName]._decRefCount();
  58904. }
  58905. }
  58906. };
  58907. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  58908. if (this._singleInstance) {
  58909. return this._postProcesses[0];
  58910. }
  58911. else {
  58912. if (!camera) {
  58913. return null;
  58914. }
  58915. return this._postProcesses[camera.name];
  58916. }
  58917. };
  58918. PostProcessRenderEffect.prototype._linkParameters = function () {
  58919. var _this = this;
  58920. for (var index in this._postProcesses) {
  58921. if (this.applyParameters) {
  58922. this.applyParameters(this._postProcesses[index]);
  58923. }
  58924. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  58925. _this._linkTextures(effect);
  58926. });
  58927. }
  58928. };
  58929. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  58930. for (var renderPassName in this._renderPasses) {
  58931. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  58932. }
  58933. for (var renderEffectName in this._renderEffectAsPasses) {
  58934. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  58935. }
  58936. };
  58937. return PostProcessRenderEffect;
  58938. }());
  58939. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  58940. })(BABYLON || (BABYLON = {}));
  58941. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  58942. var BABYLON;
  58943. (function (BABYLON) {
  58944. var PostProcessRenderPipeline = /** @class */ (function () {
  58945. function PostProcessRenderPipeline(engine, name) {
  58946. this._engine = engine;
  58947. this._name = name;
  58948. this._renderEffects = {};
  58949. this._renderEffectsForIsolatedPass = new Array();
  58950. this._cameras = [];
  58951. }
  58952. PostProcessRenderPipeline.prototype.getClassName = function () {
  58953. return "PostProcessRenderPipeline";
  58954. };
  58955. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  58956. get: function () {
  58957. for (var renderEffectName in this._renderEffects) {
  58958. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  58959. if (!this._renderEffects[renderEffectName].isSupported) {
  58960. return false;
  58961. }
  58962. }
  58963. }
  58964. return true;
  58965. },
  58966. enumerable: true,
  58967. configurable: true
  58968. });
  58969. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  58970. this._renderEffects[renderEffect._name] = renderEffect;
  58971. };
  58972. // private
  58973. PostProcessRenderPipeline.prototype._rebuild = function () {
  58974. };
  58975. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  58976. var renderEffects = this._renderEffects[renderEffectName];
  58977. if (!renderEffects) {
  58978. return;
  58979. }
  58980. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  58981. };
  58982. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  58983. var renderEffects = this._renderEffects[renderEffectName];
  58984. if (!renderEffects) {
  58985. return;
  58986. }
  58987. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  58988. };
  58989. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  58990. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  58991. if (!cams) {
  58992. return;
  58993. }
  58994. var indicesToDelete = [];
  58995. var i;
  58996. for (i = 0; i < cams.length; i++) {
  58997. var camera = cams[i];
  58998. var cameraName = camera.name;
  58999. if (this._cameras.indexOf(camera) === -1) {
  59000. this._cameras[cameraName] = camera;
  59001. }
  59002. else if (unique) {
  59003. indicesToDelete.push(i);
  59004. }
  59005. }
  59006. for (i = 0; i < indicesToDelete.length; i++) {
  59007. cameras.splice(indicesToDelete[i], 1);
  59008. }
  59009. for (var renderEffectName in this._renderEffects) {
  59010. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  59011. this._renderEffects[renderEffectName]._attachCameras(cams);
  59012. }
  59013. }
  59014. };
  59015. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  59016. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  59017. if (!cams) {
  59018. return;
  59019. }
  59020. for (var renderEffectName in this._renderEffects) {
  59021. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  59022. this._renderEffects[renderEffectName]._detachCameras(cams);
  59023. }
  59024. }
  59025. for (var i = 0; i < cams.length; i++) {
  59026. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  59027. }
  59028. };
  59029. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  59030. var _this = this;
  59031. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  59032. if (!cams) {
  59033. return;
  59034. }
  59035. var pass = null;
  59036. var renderEffectName;
  59037. for (renderEffectName in this._renderEffects) {
  59038. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  59039. pass = this._renderEffects[renderEffectName].getPass(passName);
  59040. if (pass != null) {
  59041. break;
  59042. }
  59043. }
  59044. }
  59045. if (pass === null) {
  59046. return;
  59047. }
  59048. for (renderEffectName in this._renderEffects) {
  59049. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  59050. this._renderEffects[renderEffectName]._disable(cams);
  59051. }
  59052. }
  59053. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  59054. for (var i = 0; i < cams.length; i++) {
  59055. var camera = cams[i];
  59056. var cameraName = camera.name;
  59057. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () { return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, undefined, _this._engine, true); });
  59058. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  59059. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  59060. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  59061. }
  59062. };
  59063. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  59064. var _this = this;
  59065. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  59066. if (!cams) {
  59067. return;
  59068. }
  59069. for (var i = 0; i < cams.length; i++) {
  59070. var camera = cams[i];
  59071. var cameraName = camera.name;
  59072. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () { return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, undefined, _this._engine, true); });
  59073. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  59074. }
  59075. for (var renderEffectName in this._renderEffects) {
  59076. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  59077. this._renderEffects[renderEffectName]._enable(cams);
  59078. }
  59079. }
  59080. };
  59081. PostProcessRenderPipeline.prototype._update = function () {
  59082. for (var renderEffectName in this._renderEffects) {
  59083. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  59084. this._renderEffects[renderEffectName]._update();
  59085. }
  59086. }
  59087. for (var i = 0; i < this._cameras.length; i++) {
  59088. var cameraName = this._cameras[i].name;
  59089. if (this._renderEffectsForIsolatedPass[cameraName]) {
  59090. this._renderEffectsForIsolatedPass[cameraName]._update();
  59091. }
  59092. }
  59093. };
  59094. PostProcessRenderPipeline.prototype._reset = function () {
  59095. this._renderEffects = {};
  59096. this._renderEffectsForIsolatedPass = new Array();
  59097. };
  59098. PostProcessRenderPipeline.prototype.dispose = function () {
  59099. // Must be implemented by children
  59100. };
  59101. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  59102. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  59103. __decorate([
  59104. BABYLON.serialize()
  59105. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  59106. return PostProcessRenderPipeline;
  59107. }());
  59108. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  59109. })(BABYLON || (BABYLON = {}));
  59110. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  59111. var BABYLON;
  59112. (function (BABYLON) {
  59113. var DepthRenderer = /** @class */ (function () {
  59114. function DepthRenderer(scene, type) {
  59115. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  59116. var _this = this;
  59117. this._scene = scene;
  59118. var engine = scene.getEngine();
  59119. // Render target
  59120. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  59121. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59122. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59123. this._depthMap.refreshRate = 1;
  59124. this._depthMap.renderParticles = false;
  59125. this._depthMap.renderList = null;
  59126. // set default depth value to 1.0 (far away)
  59127. this._depthMap.onClearObservable.add(function (engine) {
  59128. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  59129. });
  59130. // Custom render function
  59131. var renderSubMesh = function (subMesh) {
  59132. var mesh = subMesh.getRenderingMesh();
  59133. var scene = _this._scene;
  59134. var engine = scene.getEngine();
  59135. var material = subMesh.getMaterial();
  59136. if (!material) {
  59137. return;
  59138. }
  59139. // Culling and reverse (right handed system)
  59140. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  59141. // Managing instances
  59142. var batch = mesh._getInstancesRenderList(subMesh._id);
  59143. if (batch.mustReturn) {
  59144. return;
  59145. }
  59146. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  59147. if (_this.isReady(subMesh, hardwareInstancedRendering) && scene.activeCamera) {
  59148. engine.enableEffect(_this._effect);
  59149. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  59150. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  59151. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.minZ + scene.activeCamera.maxZ);
  59152. // Alpha test
  59153. if (material && material.needAlphaTesting()) {
  59154. var alphaTexture = material.getAlphaTestTexture();
  59155. if (alphaTexture) {
  59156. _this._effect.setTexture("diffuseSampler", alphaTexture);
  59157. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  59158. }
  59159. }
  59160. // Bones
  59161. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  59162. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  59163. }
  59164. // Draw
  59165. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  59166. }
  59167. };
  59168. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  59169. var index;
  59170. if (depthOnlySubMeshes.length) {
  59171. engine.setColorWrite(false);
  59172. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  59173. renderSubMesh(depthOnlySubMeshes.data[index]);
  59174. }
  59175. engine.setColorWrite(true);
  59176. }
  59177. for (index = 0; index < opaqueSubMeshes.length; index++) {
  59178. renderSubMesh(opaqueSubMeshes.data[index]);
  59179. }
  59180. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  59181. renderSubMesh(alphaTestSubMeshes.data[index]);
  59182. }
  59183. };
  59184. }
  59185. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  59186. var material = subMesh.getMaterial();
  59187. if (material.disableDepthWrite) {
  59188. return false;
  59189. }
  59190. var defines = [];
  59191. var attribs = [BABYLON.VertexBuffer.PositionKind];
  59192. var mesh = subMesh.getMesh();
  59193. // Alpha test
  59194. if (material && material.needAlphaTesting()) {
  59195. defines.push("#define ALPHATEST");
  59196. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  59197. attribs.push(BABYLON.VertexBuffer.UVKind);
  59198. defines.push("#define UV1");
  59199. }
  59200. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  59201. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  59202. defines.push("#define UV2");
  59203. }
  59204. }
  59205. // Bones
  59206. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  59207. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  59208. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  59209. if (mesh.numBoneInfluencers > 4) {
  59210. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  59211. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  59212. }
  59213. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  59214. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  59215. }
  59216. else {
  59217. defines.push("#define NUM_BONE_INFLUENCERS 0");
  59218. }
  59219. // Instances
  59220. if (useInstances) {
  59221. defines.push("#define INSTANCES");
  59222. attribs.push("world0");
  59223. attribs.push("world1");
  59224. attribs.push("world2");
  59225. attribs.push("world3");
  59226. }
  59227. // Get correct effect
  59228. var join = defines.join("\n");
  59229. if (this._cachedDefines !== join) {
  59230. this._cachedDefines = join;
  59231. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  59232. }
  59233. return this._effect.isReady();
  59234. };
  59235. DepthRenderer.prototype.getDepthMap = function () {
  59236. return this._depthMap;
  59237. };
  59238. // Methods
  59239. DepthRenderer.prototype.dispose = function () {
  59240. this._depthMap.dispose();
  59241. };
  59242. return DepthRenderer;
  59243. }());
  59244. BABYLON.DepthRenderer = DepthRenderer;
  59245. })(BABYLON || (BABYLON = {}));
  59246. //# sourceMappingURL=babylon.depthRenderer.js.map
  59247. var BABYLON;
  59248. (function (BABYLON) {
  59249. var SSAORenderingPipeline = /** @class */ (function (_super) {
  59250. __extends(SSAORenderingPipeline, _super);
  59251. /**
  59252. * @constructor
  59253. * @param {string} name - The rendering pipeline name
  59254. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  59255. * @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 }
  59256. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  59257. */
  59258. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  59259. var _this = _super.call(this, scene.getEngine(), name) || this;
  59260. // Members
  59261. /**
  59262. * The PassPostProcess id in the pipeline that contains the original scene color
  59263. * @type {string}
  59264. */
  59265. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  59266. /**
  59267. * The SSAO PostProcess id in the pipeline
  59268. * @type {string}
  59269. */
  59270. _this.SSAORenderEffect = "SSAORenderEffect";
  59271. /**
  59272. * The horizontal blur PostProcess id in the pipeline
  59273. * @type {string}
  59274. */
  59275. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  59276. /**
  59277. * The vertical blur PostProcess id in the pipeline
  59278. * @type {string}
  59279. */
  59280. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  59281. /**
  59282. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  59283. * @type {string}
  59284. */
  59285. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  59286. /**
  59287. * The output strength of the SSAO post-process. Default value is 1.0.
  59288. * @type {number}
  59289. */
  59290. _this.totalStrength = 1.0;
  59291. /**
  59292. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  59293. * @type {number}
  59294. */
  59295. _this.radius = 0.0001;
  59296. /**
  59297. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  59298. * Must not be equal to fallOff and superior to fallOff.
  59299. * Default value is 0.975
  59300. * @type {number}
  59301. */
  59302. _this.area = 0.0075;
  59303. /**
  59304. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  59305. * Must not be equal to area and inferior to area.
  59306. * Default value is 0.0
  59307. * @type {number}
  59308. */
  59309. _this.fallOff = 0.000001;
  59310. /**
  59311. * The base color of the SSAO post-process
  59312. * The final result is "base + ssao" between [0, 1]
  59313. * @type {number}
  59314. */
  59315. _this.base = 0.5;
  59316. _this._firstUpdate = true;
  59317. _this._scene = scene;
  59318. // Set up assets
  59319. _this._createRandomTexture();
  59320. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  59321. var ssaoRatio = ratio.ssaoRatio || ratio;
  59322. var combineRatio = ratio.combineRatio || ratio;
  59323. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  59324. _this._createSSAOPostProcess(ssaoRatio);
  59325. _this._createBlurPostProcess(ssaoRatio);
  59326. _this._createSSAOCombinePostProcess(combineRatio);
  59327. // Set up pipeline
  59328. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  59329. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  59330. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  59331. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  59332. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  59333. // Finish
  59334. scene.postProcessRenderPipelineManager.addPipeline(_this);
  59335. if (cameras)
  59336. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  59337. return _this;
  59338. }
  59339. // Public Methods
  59340. /**
  59341. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  59342. */
  59343. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  59344. if (disableDepthRender === void 0) { disableDepthRender = false; }
  59345. for (var i = 0; i < this._scene.cameras.length; i++) {
  59346. var camera = this._scene.cameras[i];
  59347. this._originalColorPostProcess.dispose(camera);
  59348. this._ssaoPostProcess.dispose(camera);
  59349. this._blurHPostProcess.dispose(camera);
  59350. this._blurVPostProcess.dispose(camera);
  59351. this._ssaoCombinePostProcess.dispose(camera);
  59352. }
  59353. this._randomTexture.dispose();
  59354. if (disableDepthRender)
  59355. this._scene.disableDepthRenderer();
  59356. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  59357. _super.prototype.dispose.call(this);
  59358. };
  59359. // Private Methods
  59360. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  59361. var _this = this;
  59362. var size = 16;
  59363. 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);
  59364. 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);
  59365. this._blurHPostProcess.onActivateObservable.add(function () {
  59366. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  59367. _this._blurHPostProcess.kernel = size * dw;
  59368. });
  59369. this._blurVPostProcess.onActivateObservable.add(function () {
  59370. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  59371. _this._blurVPostProcess.kernel = size * dw;
  59372. });
  59373. };
  59374. SSAORenderingPipeline.prototype._rebuild = function () {
  59375. this._firstUpdate = true;
  59376. _super.prototype._rebuild.call(this);
  59377. };
  59378. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  59379. var _this = this;
  59380. var numSamples = 16;
  59381. var sampleSphere = [
  59382. 0.5381, 0.1856, -0.4319,
  59383. 0.1379, 0.2486, 0.4430,
  59384. 0.3371, 0.5679, -0.0057,
  59385. -0.6999, -0.0451, -0.0019,
  59386. 0.0689, -0.1598, -0.8547,
  59387. 0.0560, 0.0069, -0.1843,
  59388. -0.0146, 0.1402, 0.0762,
  59389. 0.0100, -0.1924, -0.0344,
  59390. -0.3577, -0.5301, -0.4358,
  59391. -0.3169, 0.1063, 0.0158,
  59392. 0.0103, -0.5869, 0.0046,
  59393. -0.0897, -0.4940, 0.3287,
  59394. 0.7119, -0.0154, -0.0918,
  59395. -0.0533, 0.0596, -0.5411,
  59396. 0.0352, -0.0631, 0.5460,
  59397. -0.4776, 0.2847, -0.0271
  59398. ];
  59399. var samplesFactor = 1.0 / numSamples;
  59400. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  59401. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  59402. "area", "fallOff", "base", "range", "viewport"
  59403. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  59404. this._ssaoPostProcess.onApply = function (effect) {
  59405. if (_this._firstUpdate) {
  59406. effect.setArray3("sampleSphere", sampleSphere);
  59407. effect.setFloat("samplesFactor", samplesFactor);
  59408. effect.setFloat("randTextureTiles", 4.0);
  59409. }
  59410. effect.setFloat("totalStrength", _this.totalStrength);
  59411. effect.setFloat("radius", _this.radius);
  59412. effect.setFloat("area", _this.area);
  59413. effect.setFloat("fallOff", _this.fallOff);
  59414. effect.setFloat("base", _this.base);
  59415. effect.setTexture("textureSampler", _this._depthTexture);
  59416. effect.setTexture("randomSampler", _this._randomTexture);
  59417. };
  59418. };
  59419. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  59420. var _this = this;
  59421. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  59422. this._ssaoCombinePostProcess.onApply = function (effect) {
  59423. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  59424. };
  59425. };
  59426. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  59427. var size = 512;
  59428. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  59429. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  59430. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  59431. var context = this._randomTexture.getContext();
  59432. var rand = function (min, max) {
  59433. return Math.random() * (max - min) + min;
  59434. };
  59435. var randVector = BABYLON.Vector3.Zero();
  59436. for (var x = 0; x < size; x++) {
  59437. for (var y = 0; y < size; y++) {
  59438. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  59439. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  59440. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  59441. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  59442. context.fillRect(x, y, 1, 1);
  59443. }
  59444. }
  59445. this._randomTexture.update(false);
  59446. };
  59447. __decorate([
  59448. BABYLON.serialize()
  59449. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  59450. __decorate([
  59451. BABYLON.serialize()
  59452. ], SSAORenderingPipeline.prototype, "radius", void 0);
  59453. __decorate([
  59454. BABYLON.serialize()
  59455. ], SSAORenderingPipeline.prototype, "area", void 0);
  59456. __decorate([
  59457. BABYLON.serialize()
  59458. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  59459. __decorate([
  59460. BABYLON.serialize()
  59461. ], SSAORenderingPipeline.prototype, "base", void 0);
  59462. return SSAORenderingPipeline;
  59463. }(BABYLON.PostProcessRenderPipeline));
  59464. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  59465. })(BABYLON || (BABYLON = {}));
  59466. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  59467. var BABYLON;
  59468. (function (BABYLON) {
  59469. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  59470. __extends(SSAO2RenderingPipeline, _super);
  59471. /**
  59472. * @constructor
  59473. * @param {string} name - The rendering pipeline name
  59474. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  59475. * @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 }
  59476. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  59477. */
  59478. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  59479. var _this = _super.call(this, scene.getEngine(), name) || this;
  59480. // Members
  59481. /**
  59482. * The PassPostProcess id in the pipeline that contains the original scene color
  59483. * @type {string}
  59484. */
  59485. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  59486. /**
  59487. * The SSAO PostProcess id in the pipeline
  59488. * @type {string}
  59489. */
  59490. _this.SSAORenderEffect = "SSAORenderEffect";
  59491. /**
  59492. * The horizontal blur PostProcess id in the pipeline
  59493. * @type {string}
  59494. */
  59495. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  59496. /**
  59497. * The vertical blur PostProcess id in the pipeline
  59498. * @type {string}
  59499. */
  59500. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  59501. /**
  59502. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  59503. * @type {string}
  59504. */
  59505. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  59506. /**
  59507. * The output strength of the SSAO post-process. Default value is 1.0.
  59508. * @type {number}
  59509. */
  59510. _this.totalStrength = 1.0;
  59511. /**
  59512. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  59513. * @type {number}
  59514. */
  59515. _this.maxZ = 100.0;
  59516. /**
  59517. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  59518. * @type {number}
  59519. */
  59520. _this.minZAspect = 0.2;
  59521. /**
  59522. * Number of samples used for the SSAO calculations. Default value is 8
  59523. * @type {number}
  59524. */
  59525. _this._samples = 8;
  59526. /**
  59527. * Are we using bilateral blur ?
  59528. * @type {boolean}
  59529. */
  59530. _this._expensiveBlur = true;
  59531. /**
  59532. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  59533. * @type {number}
  59534. */
  59535. _this.radius = 2.0;
  59536. /**
  59537. * The base color of the SSAO post-process
  59538. * The final result is "base + ssao" between [0, 1]
  59539. * @type {number}
  59540. */
  59541. _this.base = 0.1;
  59542. _this._firstUpdate = true;
  59543. _this._scene = scene;
  59544. if (!_this.isSupported) {
  59545. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  59546. return _this;
  59547. }
  59548. var ssaoRatio = ratio.ssaoRatio || ratio;
  59549. var blurRatio = ratio.blurRatio || ratio;
  59550. // Set up assets
  59551. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  59552. _this._createRandomTexture();
  59553. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  59554. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  59555. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  59556. _this._createSSAOPostProcess(1.0);
  59557. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  59558. _this._createSSAOCombinePostProcess(blurRatio);
  59559. // Set up pipeline
  59560. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  59561. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  59562. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  59563. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  59564. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  59565. // Finish
  59566. scene.postProcessRenderPipelineManager.addPipeline(_this);
  59567. if (cameras)
  59568. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  59569. return _this;
  59570. }
  59571. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  59572. get: function () {
  59573. return this._samples;
  59574. },
  59575. set: function (n) {
  59576. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  59577. this._samples = n;
  59578. this._sampleSphere = this._generateHemisphere();
  59579. this._firstUpdate = true;
  59580. },
  59581. enumerable: true,
  59582. configurable: true
  59583. });
  59584. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  59585. get: function () {
  59586. return this._expensiveBlur;
  59587. },
  59588. set: function (b) {
  59589. 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"]);
  59590. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  59591. this._expensiveBlur = b;
  59592. this._firstUpdate = true;
  59593. },
  59594. enumerable: true,
  59595. configurable: true
  59596. });
  59597. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  59598. /**
  59599. * Support test.
  59600. * @type {boolean}
  59601. */
  59602. get: function () {
  59603. var engine = BABYLON.Engine.LastCreatedEngine;
  59604. if (!engine) {
  59605. return false;
  59606. }
  59607. return engine.getCaps().drawBuffersExtension;
  59608. },
  59609. enumerable: true,
  59610. configurable: true
  59611. });
  59612. // Public Methods
  59613. /**
  59614. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  59615. */
  59616. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  59617. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  59618. for (var i = 0; i < this._scene.cameras.length; i++) {
  59619. var camera = this._scene.cameras[i];
  59620. this._originalColorPostProcess.dispose(camera);
  59621. this._ssaoPostProcess.dispose(camera);
  59622. this._blurHPostProcess.dispose(camera);
  59623. this._blurVPostProcess.dispose(camera);
  59624. this._ssaoCombinePostProcess.dispose(camera);
  59625. }
  59626. this._randomTexture.dispose();
  59627. if (disableGeometryBufferRenderer)
  59628. this._scene.disableGeometryBufferRenderer();
  59629. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  59630. _super.prototype.dispose.call(this);
  59631. };
  59632. // Private Methods
  59633. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  59634. var _this = this;
  59635. this._samplerOffsets = [];
  59636. var expensive = this.expensiveBlur;
  59637. for (var i = -8; i < 8; i++) {
  59638. this._samplerOffsets.push(i * 2 + 0.5);
  59639. }
  59640. 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");
  59641. this._blurHPostProcess.onApply = function (effect) {
  59642. if (!_this._scene.activeCamera) {
  59643. return;
  59644. }
  59645. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  59646. effect.setFloat("near", _this._scene.activeCamera.minZ);
  59647. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  59648. effect.setFloat("radius", _this.radius);
  59649. effect.setTexture("depthSampler", _this._depthTexture);
  59650. if (_this._firstUpdate) {
  59651. effect.setArray("samplerOffsets", _this._samplerOffsets);
  59652. }
  59653. };
  59654. 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");
  59655. this._blurVPostProcess.onApply = function (effect) {
  59656. if (!_this._scene.activeCamera) {
  59657. return;
  59658. }
  59659. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  59660. effect.setFloat("near", _this._scene.activeCamera.minZ);
  59661. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  59662. effect.setFloat("radius", _this.radius);
  59663. effect.setTexture("depthSampler", _this._depthTexture);
  59664. if (_this._firstUpdate) {
  59665. effect.setArray("samplerOffsets", _this._samplerOffsets);
  59666. _this._firstUpdate = false;
  59667. }
  59668. };
  59669. };
  59670. SSAO2RenderingPipeline.prototype._rebuild = function () {
  59671. this._firstUpdate = true;
  59672. _super.prototype._rebuild.call(this);
  59673. };
  59674. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  59675. var numSamples = this.samples;
  59676. var result = [];
  59677. var vector, scale;
  59678. var rand = function (min, max) {
  59679. return Math.random() * (max - min) + min;
  59680. };
  59681. var i = 0;
  59682. while (i < numSamples) {
  59683. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  59684. vector.normalize();
  59685. scale = i / numSamples;
  59686. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  59687. vector.scaleInPlace(scale);
  59688. result.push(vector.x, vector.y, vector.z);
  59689. i++;
  59690. }
  59691. return result;
  59692. };
  59693. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  59694. var _this = this;
  59695. var numSamples = this.samples;
  59696. this._sampleSphere = this._generateHemisphere();
  59697. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  59698. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  59699. "base", "range", "projection", "near", "far", "texelSize",
  59700. "xViewport", "yViewport", "maxZ", "minZAspect"
  59701. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  59702. this._ssaoPostProcess.onApply = function (effect) {
  59703. if (_this._firstUpdate) {
  59704. effect.setArray3("sampleSphere", _this._sampleSphere);
  59705. effect.setFloat("randTextureTiles", 4.0);
  59706. }
  59707. if (!_this._scene.activeCamera) {
  59708. return;
  59709. }
  59710. effect.setFloat("samplesFactor", 1 / _this.samples);
  59711. effect.setFloat("totalStrength", _this.totalStrength);
  59712. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  59713. effect.setFloat("radius", _this.radius);
  59714. effect.setFloat("maxZ", _this.maxZ);
  59715. effect.setFloat("minZAspect", _this.minZAspect);
  59716. effect.setFloat("base", _this.base);
  59717. effect.setFloat("near", _this._scene.activeCamera.minZ);
  59718. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  59719. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  59720. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  59721. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  59722. effect.setTexture("textureSampler", _this._depthTexture);
  59723. effect.setTexture("normalSampler", _this._normalTexture);
  59724. effect.setTexture("randomSampler", _this._randomTexture);
  59725. };
  59726. };
  59727. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  59728. var _this = this;
  59729. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  59730. this._ssaoCombinePostProcess.onApply = function (effect) {
  59731. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  59732. };
  59733. };
  59734. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  59735. var size = 512;
  59736. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  59737. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  59738. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  59739. var context = this._randomTexture.getContext();
  59740. var rand = function (min, max) {
  59741. return Math.random() * (max - min) + min;
  59742. };
  59743. var randVector = BABYLON.Vector3.Zero();
  59744. for (var x = 0; x < size; x++) {
  59745. for (var y = 0; y < size; y++) {
  59746. randVector.x = rand(0.0, 1.0);
  59747. randVector.y = rand(0.0, 1.0);
  59748. randVector.z = 0.0;
  59749. randVector.normalize();
  59750. randVector.scaleInPlace(255);
  59751. randVector.x = Math.floor(randVector.x);
  59752. randVector.y = Math.floor(randVector.y);
  59753. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  59754. context.fillRect(x, y, 1, 1);
  59755. }
  59756. }
  59757. this._randomTexture.update(false);
  59758. };
  59759. __decorate([
  59760. BABYLON.serialize()
  59761. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  59762. __decorate([
  59763. BABYLON.serialize()
  59764. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  59765. __decorate([
  59766. BABYLON.serialize()
  59767. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  59768. __decorate([
  59769. BABYLON.serialize("samples")
  59770. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  59771. __decorate([
  59772. BABYLON.serialize("expensiveBlur")
  59773. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  59774. __decorate([
  59775. BABYLON.serialize()
  59776. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  59777. __decorate([
  59778. BABYLON.serialize()
  59779. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  59780. return SSAO2RenderingPipeline;
  59781. }(BABYLON.PostProcessRenderPipeline));
  59782. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  59783. })(BABYLON || (BABYLON = {}));
  59784. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  59785. // BABYLON.JS Chromatic Aberration GLSL Shader
  59786. // Author: Olivier Guyot
  59787. // Separates very slightly R, G and B colors on the edges of the screen
  59788. // Inspired by Francois Tarlier & Martins Upitis
  59789. var BABYLON;
  59790. (function (BABYLON) {
  59791. var LensRenderingPipeline = /** @class */ (function (_super) {
  59792. __extends(LensRenderingPipeline, _super);
  59793. /**
  59794. * @constructor
  59795. *
  59796. * Effect parameters are as follow:
  59797. * {
  59798. * chromatic_aberration: number; // from 0 to x (1 for realism)
  59799. * edge_blur: number; // from 0 to x (1 for realism)
  59800. * distortion: number; // from 0 to x (1 for realism)
  59801. * grain_amount: number; // from 0 to 1
  59802. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  59803. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  59804. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  59805. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  59806. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  59807. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  59808. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  59809. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  59810. * }
  59811. * Note: if an effect parameter is unset, effect is disabled
  59812. *
  59813. * @param {string} name - The rendering pipeline name
  59814. * @param {object} parameters - An object containing all parameters (see above)
  59815. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  59816. * @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)
  59817. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  59818. */
  59819. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  59820. if (ratio === void 0) { ratio = 1.0; }
  59821. var _this = _super.call(this, scene.getEngine(), name) || this;
  59822. // Lens effects can be of the following:
  59823. // - chromatic aberration (slight shift of RGB colors)
  59824. // - blur on the edge of the lens
  59825. // - lens distortion
  59826. // - depth-of-field blur & highlights enhancing
  59827. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  59828. // - grain effect (noise or custom texture)
  59829. // Two additional texture samplers are needed:
  59830. // - depth map (for depth-of-field)
  59831. // - grain texture
  59832. /**
  59833. * The chromatic aberration PostProcess id in the pipeline
  59834. * @type {string}
  59835. */
  59836. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  59837. /**
  59838. * The highlights enhancing PostProcess id in the pipeline
  59839. * @type {string}
  59840. */
  59841. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  59842. /**
  59843. * The depth-of-field PostProcess id in the pipeline
  59844. * @type {string}
  59845. */
  59846. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  59847. _this._scene = scene;
  59848. // Fetch texture samplers
  59849. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  59850. if (parameters.grain_texture) {
  59851. _this._grainTexture = parameters.grain_texture;
  59852. }
  59853. else {
  59854. _this._createGrainTexture();
  59855. }
  59856. // save parameters
  59857. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  59858. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  59859. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  59860. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  59861. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  59862. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  59863. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  59864. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  59865. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  59866. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  59867. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  59868. // Create effects
  59869. _this._createChromaticAberrationPostProcess(ratio);
  59870. _this._createHighlightsPostProcess(ratio);
  59871. _this._createDepthOfFieldPostProcess(ratio / 4);
  59872. // Set up pipeline
  59873. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  59874. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  59875. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  59876. if (_this._highlightsGain === -1) {
  59877. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  59878. }
  59879. // Finish
  59880. scene.postProcessRenderPipelineManager.addPipeline(_this);
  59881. if (cameras) {
  59882. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  59883. }
  59884. return _this;
  59885. }
  59886. // public methods (self explanatory)
  59887. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  59888. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  59889. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  59890. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  59891. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  59892. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  59893. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  59894. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  59895. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  59896. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  59897. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  59898. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  59899. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  59900. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  59901. };
  59902. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  59903. this._highlightsPostProcess.updateEffect();
  59904. };
  59905. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  59906. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  59907. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  59908. this._highlightsGain = amount;
  59909. };
  59910. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  59911. if (this._highlightsGain === -1) {
  59912. this._highlightsGain = 1.0;
  59913. }
  59914. this._highlightsThreshold = amount;
  59915. };
  59916. LensRenderingPipeline.prototype.disableHighlights = function () {
  59917. this._highlightsGain = -1;
  59918. };
  59919. /**
  59920. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  59921. */
  59922. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  59923. if (disableDepthRender === void 0) { disableDepthRender = false; }
  59924. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  59925. this._chromaticAberrationPostProcess = null;
  59926. this._highlightsPostProcess = null;
  59927. this._depthOfFieldPostProcess = null;
  59928. this._grainTexture.dispose();
  59929. if (disableDepthRender)
  59930. this._scene.disableDepthRenderer();
  59931. };
  59932. // colors shifting and distortion
  59933. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  59934. var _this = this;
  59935. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  59936. [], // samplers
  59937. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  59938. this._chromaticAberrationPostProcess.onApply = function (effect) {
  59939. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  59940. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  59941. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  59942. };
  59943. };
  59944. // highlights enhancing
  59945. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  59946. var _this = this;
  59947. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  59948. [], // samplers
  59949. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  59950. this._highlightsPostProcess.onApply = function (effect) {
  59951. effect.setFloat('gain', _this._highlightsGain);
  59952. effect.setFloat('threshold', _this._highlightsThreshold);
  59953. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  59954. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  59955. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  59956. };
  59957. };
  59958. // colors shifting and distortion
  59959. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  59960. var _this = this;
  59961. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  59962. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  59963. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  59964. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  59965. this._depthOfFieldPostProcess.onApply = function (effect) {
  59966. effect.setTexture("depthSampler", _this._depthTexture);
  59967. effect.setTexture("grainSampler", _this._grainTexture);
  59968. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  59969. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  59970. effect.setFloat('grain_amount', _this._grainAmount);
  59971. effect.setBool('blur_noise', _this._blurNoise);
  59972. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  59973. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  59974. effect.setFloat('distortion', _this._distortion);
  59975. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  59976. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  59977. effect.setFloat('aperture', _this._dofAperture);
  59978. effect.setFloat('darken', _this._dofDarken);
  59979. effect.setFloat('edge_blur', _this._edgeBlur);
  59980. effect.setBool('highlights', (_this._highlightsGain !== -1));
  59981. if (_this._scene.activeCamera) {
  59982. effect.setFloat('near', _this._scene.activeCamera.minZ);
  59983. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  59984. }
  59985. };
  59986. };
  59987. // creates a black and white random noise texture, 512x512
  59988. LensRenderingPipeline.prototype._createGrainTexture = function () {
  59989. var size = 512;
  59990. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  59991. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  59992. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  59993. var context = this._grainTexture.getContext();
  59994. var rand = function (min, max) {
  59995. return Math.random() * (max - min) + min;
  59996. };
  59997. var value;
  59998. for (var x = 0; x < size; x++) {
  59999. for (var y = 0; y < size; y++) {
  60000. value = Math.floor(rand(0.42, 0.58) * 255);
  60001. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  60002. context.fillRect(x, y, 1, 1);
  60003. }
  60004. }
  60005. this._grainTexture.update(false);
  60006. };
  60007. return LensRenderingPipeline;
  60008. }(BABYLON.PostProcessRenderPipeline));
  60009. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  60010. })(BABYLON || (BABYLON = {}));
  60011. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  60012. var BABYLON;
  60013. (function (BABYLON) {
  60014. var StandardRenderingPipeline = /** @class */ (function (_super) {
  60015. __extends(StandardRenderingPipeline, _super);
  60016. /**
  60017. * @constructor
  60018. * @param {string} name - The rendering pipeline name
  60019. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  60020. * @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)
  60021. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  60022. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  60023. */
  60024. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  60025. if (originalPostProcess === void 0) { originalPostProcess = null; }
  60026. var _this = _super.call(this, scene.getEngine(), name) || this;
  60027. _this.downSampleX4PostProcess = null;
  60028. _this.brightPassPostProcess = null;
  60029. _this.blurHPostProcesses = [];
  60030. _this.blurVPostProcesses = [];
  60031. _this.textureAdderPostProcess = null;
  60032. _this.volumetricLightPostProcess = null;
  60033. _this.volumetricLightSmoothXPostProcess = null;
  60034. _this.volumetricLightSmoothYPostProcess = null;
  60035. _this.volumetricLightMergePostProces = null;
  60036. _this.volumetricLightFinalPostProcess = null;
  60037. _this.luminancePostProcess = null;
  60038. _this.luminanceDownSamplePostProcesses = [];
  60039. _this.hdrPostProcess = null;
  60040. _this.textureAdderFinalPostProcess = null;
  60041. _this.lensFlareFinalPostProcess = null;
  60042. _this.hdrFinalPostProcess = null;
  60043. _this.lensFlarePostProcess = null;
  60044. _this.lensFlareComposePostProcess = null;
  60045. _this.motionBlurPostProcess = null;
  60046. _this.depthOfFieldPostProcess = null;
  60047. // Values
  60048. _this.brightThreshold = 1.0;
  60049. _this.blurWidth = 512.0;
  60050. _this.horizontalBlur = false;
  60051. _this.exposure = 1.0;
  60052. _this.lensTexture = null;
  60053. _this.volumetricLightCoefficient = 0.2;
  60054. _this.volumetricLightPower = 4.0;
  60055. _this.volumetricLightBlurScale = 64.0;
  60056. _this.sourceLight = null;
  60057. _this.hdrMinimumLuminance = 1.0;
  60058. _this.hdrDecreaseRate = 0.5;
  60059. _this.hdrIncreaseRate = 0.5;
  60060. _this.lensColorTexture = null;
  60061. _this.lensFlareStrength = 20.0;
  60062. _this.lensFlareGhostDispersal = 1.4;
  60063. _this.lensFlareHaloWidth = 0.7;
  60064. _this.lensFlareDistortionStrength = 16.0;
  60065. _this.lensStarTexture = null;
  60066. _this.lensFlareDirtTexture = null;
  60067. _this.depthOfFieldDistance = 10.0;
  60068. _this.depthOfFieldBlurWidth = 64.0;
  60069. _this.motionStrength = 1.0;
  60070. // IAnimatable
  60071. _this.animations = [];
  60072. _this._currentDepthOfFieldSource = null;
  60073. _this._hdrCurrentLuminance = 1.0;
  60074. // Getters and setters
  60075. _this._bloomEnabled = true;
  60076. _this._depthOfFieldEnabled = false;
  60077. _this._vlsEnabled = false;
  60078. _this._lensFlareEnabled = false;
  60079. _this._hdrEnabled = false;
  60080. _this._motionBlurEnabled = false;
  60081. _this._motionBlurSamples = 64.0;
  60082. _this._volumetricLightStepsCount = 50.0;
  60083. _this._cameras = cameras || [];
  60084. // Initialize
  60085. _this._scene = scene;
  60086. _this._basePostProcess = originalPostProcess;
  60087. _this._ratio = ratio;
  60088. // Misc
  60089. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  60090. // Finish
  60091. scene.postProcessRenderPipelineManager.addPipeline(_this);
  60092. _this._buildPipeline();
  60093. return _this;
  60094. }
  60095. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  60096. get: function () {
  60097. return this._bloomEnabled;
  60098. },
  60099. set: function (enabled) {
  60100. if (this._bloomEnabled === enabled) {
  60101. return;
  60102. }
  60103. this._bloomEnabled = enabled;
  60104. this._buildPipeline();
  60105. },
  60106. enumerable: true,
  60107. configurable: true
  60108. });
  60109. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  60110. get: function () {
  60111. return this._depthOfFieldEnabled;
  60112. },
  60113. set: function (enabled) {
  60114. if (this._depthOfFieldEnabled === enabled) {
  60115. return;
  60116. }
  60117. this._depthOfFieldEnabled = enabled;
  60118. this._buildPipeline();
  60119. },
  60120. enumerable: true,
  60121. configurable: true
  60122. });
  60123. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  60124. get: function () {
  60125. return this._lensFlareEnabled;
  60126. },
  60127. set: function (enabled) {
  60128. if (this._lensFlareEnabled === enabled) {
  60129. return;
  60130. }
  60131. this._lensFlareEnabled = enabled;
  60132. this._buildPipeline();
  60133. },
  60134. enumerable: true,
  60135. configurable: true
  60136. });
  60137. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  60138. get: function () {
  60139. return this._hdrEnabled;
  60140. },
  60141. set: function (enabled) {
  60142. if (this._hdrEnabled === enabled) {
  60143. return;
  60144. }
  60145. this._hdrEnabled = enabled;
  60146. this._buildPipeline();
  60147. },
  60148. enumerable: true,
  60149. configurable: true
  60150. });
  60151. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  60152. get: function () {
  60153. return this._vlsEnabled;
  60154. },
  60155. set: function (enabled) {
  60156. if (this._vlsEnabled === enabled) {
  60157. return;
  60158. }
  60159. if (enabled) {
  60160. var geometry = this._scene.enableGeometryBufferRenderer();
  60161. if (!geometry) {
  60162. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  60163. return;
  60164. }
  60165. }
  60166. this._vlsEnabled = enabled;
  60167. this._buildPipeline();
  60168. },
  60169. enumerable: true,
  60170. configurable: true
  60171. });
  60172. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  60173. get: function () {
  60174. return this._motionBlurEnabled;
  60175. },
  60176. set: function (enabled) {
  60177. if (this._motionBlurEnabled === enabled) {
  60178. return;
  60179. }
  60180. this._motionBlurEnabled = enabled;
  60181. this._buildPipeline();
  60182. },
  60183. enumerable: true,
  60184. configurable: true
  60185. });
  60186. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  60187. get: function () {
  60188. return this._volumetricLightStepsCount;
  60189. },
  60190. set: function (count) {
  60191. if (this.volumetricLightPostProcess) {
  60192. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  60193. }
  60194. this._volumetricLightStepsCount = count;
  60195. },
  60196. enumerable: true,
  60197. configurable: true
  60198. });
  60199. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  60200. get: function () {
  60201. return this._motionBlurSamples;
  60202. },
  60203. set: function (samples) {
  60204. if (this.motionBlurPostProcess) {
  60205. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  60206. }
  60207. this._motionBlurSamples = samples;
  60208. },
  60209. enumerable: true,
  60210. configurable: true
  60211. });
  60212. StandardRenderingPipeline.prototype._buildPipeline = function () {
  60213. var _this = this;
  60214. var ratio = this._ratio;
  60215. var scene = this._scene;
  60216. this._disposePostProcesses();
  60217. this._reset();
  60218. // Create pass post-process
  60219. if (!this._basePostProcess) {
  60220. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  60221. this.originalPostProcess.onApply = function (effect) {
  60222. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  60223. };
  60224. }
  60225. else {
  60226. this.originalPostProcess = this._basePostProcess;
  60227. }
  60228. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  60229. this._currentDepthOfFieldSource = this.originalPostProcess;
  60230. if (this._vlsEnabled) {
  60231. // Create volumetric light
  60232. this._createVolumetricLightPostProcess(scene, ratio);
  60233. // Create volumetric light final post-process
  60234. 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);
  60235. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  60236. }
  60237. if (this._bloomEnabled) {
  60238. // Create down sample X4 post-process
  60239. this._createDownSampleX4PostProcess(scene, ratio / 2);
  60240. // Create bright pass post-process
  60241. this._createBrightPassPostProcess(scene, ratio / 2);
  60242. // Create gaussian blur post-processes (down sampling blurs)
  60243. this._createBlurPostProcesses(scene, ratio / 4, 1);
  60244. // Create texture adder post-process
  60245. this._createTextureAdderPostProcess(scene, ratio);
  60246. // Create depth-of-field source post-process
  60247. 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);
  60248. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  60249. }
  60250. if (this._lensFlareEnabled) {
  60251. // Create lens flare post-process
  60252. this._createLensFlarePostProcess(scene, ratio);
  60253. // Create depth-of-field source post-process post lens-flare and disable it now
  60254. 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);
  60255. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  60256. }
  60257. if (this._hdrEnabled) {
  60258. // Create luminance
  60259. this._createLuminancePostProcesses(scene, this._floatTextureType);
  60260. // Create HDR
  60261. this._createHdrPostProcess(scene, ratio);
  60262. // Create depth-of-field source post-process post hdr and disable it now
  60263. 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);
  60264. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  60265. }
  60266. if (this._depthOfFieldEnabled) {
  60267. // Create gaussian blur used by depth-of-field
  60268. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  60269. // Create depth-of-field post-process
  60270. this._createDepthOfFieldPostProcess(scene, ratio);
  60271. }
  60272. if (this._motionBlurEnabled) {
  60273. // Create motion blur post-process
  60274. this._createMotionBlurPostProcess(scene, ratio);
  60275. }
  60276. if (this._cameras !== null) {
  60277. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  60278. }
  60279. };
  60280. // Down Sample X4 Post-Processs
  60281. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  60282. var _this = this;
  60283. var downSampleX4Offsets = new Array(32);
  60284. 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);
  60285. this.downSampleX4PostProcess.onApply = function (effect) {
  60286. var id = 0;
  60287. var width = _this.downSampleX4PostProcess.width;
  60288. var height = _this.downSampleX4PostProcess.height;
  60289. for (var i = -2; i < 2; i++) {
  60290. for (var j = -2; j < 2; j++) {
  60291. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  60292. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  60293. id += 2;
  60294. }
  60295. }
  60296. effect.setArray2("dsOffsets", downSampleX4Offsets);
  60297. };
  60298. // Add to pipeline
  60299. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  60300. };
  60301. // Brightpass Post-Process
  60302. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  60303. var _this = this;
  60304. var brightOffsets = new Array(8);
  60305. 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);
  60306. this.brightPassPostProcess.onApply = function (effect) {
  60307. var sU = (1.0 / _this.brightPassPostProcess.width);
  60308. var sV = (1.0 / _this.brightPassPostProcess.height);
  60309. brightOffsets[0] = -0.5 * sU;
  60310. brightOffsets[1] = 0.5 * sV;
  60311. brightOffsets[2] = 0.5 * sU;
  60312. brightOffsets[3] = 0.5 * sV;
  60313. brightOffsets[4] = -0.5 * sU;
  60314. brightOffsets[5] = -0.5 * sV;
  60315. brightOffsets[6] = 0.5 * sU;
  60316. brightOffsets[7] = -0.5 * sV;
  60317. effect.setArray2("dsOffsets", brightOffsets);
  60318. effect.setFloat("brightThreshold", _this.brightThreshold);
  60319. };
  60320. // Add to pipeline
  60321. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  60322. };
  60323. // Create blur H&V post-processes
  60324. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  60325. var _this = this;
  60326. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  60327. var engine = scene.getEngine();
  60328. 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);
  60329. 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);
  60330. blurX.onActivateObservable.add(function () {
  60331. var dw = blurX.width / engine.getRenderWidth();
  60332. blurX.kernel = _this[blurWidthKey] * dw;
  60333. });
  60334. blurY.onActivateObservable.add(function () {
  60335. var dw = blurY.height / engine.getRenderHeight();
  60336. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  60337. });
  60338. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  60339. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  60340. this.blurHPostProcesses.push(blurX);
  60341. this.blurVPostProcesses.push(blurY);
  60342. };
  60343. // Create texture adder post-process
  60344. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  60345. var _this = this;
  60346. 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);
  60347. this.textureAdderPostProcess.onApply = function (effect) {
  60348. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  60349. effect.setTexture("lensSampler", _this.lensTexture);
  60350. effect.setFloat("exposure", _this.exposure);
  60351. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  60352. };
  60353. // Add to pipeline
  60354. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  60355. };
  60356. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  60357. var _this = this;
  60358. var geometryRenderer = scene.enableGeometryBufferRenderer();
  60359. geometryRenderer.enablePosition = true;
  60360. var geometry = geometryRenderer.getGBuffer();
  60361. // Base post-process
  60362. 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));
  60363. var depthValues = BABYLON.Vector2.Zero();
  60364. this.volumetricLightPostProcess.onApply = function (effect) {
  60365. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  60366. var generator = _this.sourceLight.getShadowGenerator();
  60367. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  60368. effect.setTexture("positionSampler", geometry.textures[2]);
  60369. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  60370. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  60371. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  60372. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  60373. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  60374. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  60375. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  60376. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  60377. effect.setVector2("depthValues", depthValues);
  60378. }
  60379. };
  60380. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  60381. // Smooth
  60382. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  60383. // Merge
  60384. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  60385. this.volumetricLightMergePostProces.onApply = function (effect) {
  60386. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  60387. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  60388. };
  60389. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  60390. };
  60391. // Create luminance
  60392. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  60393. var _this = this;
  60394. // Create luminance
  60395. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  60396. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  60397. var offsets = [];
  60398. this.luminancePostProcess.onApply = function (effect) {
  60399. var sU = (1.0 / _this.luminancePostProcess.width);
  60400. var sV = (1.0 / _this.luminancePostProcess.height);
  60401. offsets[0] = -0.5 * sU;
  60402. offsets[1] = 0.5 * sV;
  60403. offsets[2] = 0.5 * sU;
  60404. offsets[3] = 0.5 * sV;
  60405. offsets[4] = -0.5 * sU;
  60406. offsets[5] = -0.5 * sV;
  60407. offsets[6] = 0.5 * sU;
  60408. offsets[7] = -0.5 * sV;
  60409. effect.setArray2("lumOffsets", offsets);
  60410. };
  60411. // Add to pipeline
  60412. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  60413. // Create down sample luminance
  60414. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  60415. var size = Math.pow(3, i);
  60416. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  60417. if (i === 0) {
  60418. defines += "#define FINAL_DOWN_SAMPLER";
  60419. }
  60420. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  60421. this.luminanceDownSamplePostProcesses.push(postProcess);
  60422. }
  60423. // Create callbacks and add effects
  60424. var lastLuminance = this.luminancePostProcess;
  60425. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  60426. var downSampleOffsets = new Array(18);
  60427. pp.onApply = function (effect) {
  60428. if (!lastLuminance) {
  60429. return;
  60430. }
  60431. var id = 0;
  60432. for (var x = -1; x < 2; x++) {
  60433. for (var y = -1; y < 2; y++) {
  60434. downSampleOffsets[id] = x / lastLuminance.width;
  60435. downSampleOffsets[id + 1] = y / lastLuminance.height;
  60436. id += 2;
  60437. }
  60438. }
  60439. effect.setArray2("dsOffsets", downSampleOffsets);
  60440. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  60441. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  60442. lastLuminance = _this.luminancePostProcess;
  60443. }
  60444. else {
  60445. lastLuminance = pp;
  60446. }
  60447. };
  60448. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  60449. pp.onAfterRender = function (effect) {
  60450. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  60451. 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);
  60452. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  60453. };
  60454. }
  60455. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  60456. });
  60457. };
  60458. // Create HDR post-process
  60459. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  60460. var _this = this;
  60461. 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);
  60462. var outputLiminance = 1;
  60463. var time = 0;
  60464. var lastTime = 0;
  60465. this.hdrPostProcess.onApply = function (effect) {
  60466. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  60467. time += scene.getEngine().getDeltaTime();
  60468. if (outputLiminance < 0) {
  60469. outputLiminance = _this._hdrCurrentLuminance;
  60470. }
  60471. else {
  60472. var dt = (lastTime - time) / 1000.0;
  60473. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  60474. outputLiminance += _this.hdrDecreaseRate * dt;
  60475. }
  60476. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  60477. outputLiminance -= _this.hdrIncreaseRate * dt;
  60478. }
  60479. else {
  60480. outputLiminance = _this._hdrCurrentLuminance;
  60481. }
  60482. }
  60483. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  60484. effect.setFloat("averageLuminance", outputLiminance);
  60485. lastTime = time;
  60486. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  60487. };
  60488. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  60489. };
  60490. // Create lens flare post-process
  60491. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  60492. var _this = this;
  60493. 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);
  60494. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  60495. this._createBlurPostProcesses(scene, ratio / 4, 2);
  60496. 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);
  60497. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  60498. var resolution = new BABYLON.Vector2(0, 0);
  60499. // Lens flare
  60500. this.lensFlarePostProcess.onApply = function (effect) {
  60501. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  60502. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  60503. effect.setFloat("strength", _this.lensFlareStrength);
  60504. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  60505. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  60506. // Shift
  60507. resolution.x = _this.lensFlarePostProcess.width;
  60508. resolution.y = _this.lensFlarePostProcess.height;
  60509. effect.setVector2("resolution", resolution);
  60510. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  60511. };
  60512. // Compose
  60513. 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);
  60514. 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);
  60515. this.lensFlareComposePostProcess.onApply = function (effect) {
  60516. if (!_this._scene.activeCamera) {
  60517. return;
  60518. }
  60519. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  60520. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  60521. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  60522. // Lens start rotation matrix
  60523. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  60524. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  60525. 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));
  60526. camRot *= 4.0;
  60527. 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);
  60528. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  60529. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  60530. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  60531. };
  60532. };
  60533. // Create depth-of-field post-process
  60534. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  60535. var _this = this;
  60536. 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);
  60537. this.depthOfFieldPostProcess.onApply = function (effect) {
  60538. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  60539. effect.setTexture("depthSampler", _this._getDepthTexture());
  60540. effect.setFloat("distance", _this.depthOfFieldDistance);
  60541. };
  60542. // Add to pipeline
  60543. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  60544. };
  60545. // Create motion blur post-process
  60546. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  60547. var _this = this;
  60548. 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);
  60549. var motionScale = 0;
  60550. var prevViewProjection = BABYLON.Matrix.Identity();
  60551. var invViewProjection = BABYLON.Matrix.Identity();
  60552. var viewProjection = BABYLON.Matrix.Identity();
  60553. var screenSize = BABYLON.Vector2.Zero();
  60554. this.motionBlurPostProcess.onApply = function (effect) {
  60555. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  60556. viewProjection.invertToRef(invViewProjection);
  60557. effect.setMatrix("inverseViewProjection", invViewProjection);
  60558. effect.setMatrix("prevViewProjection", prevViewProjection);
  60559. prevViewProjection = viewProjection;
  60560. screenSize.x = _this.motionBlurPostProcess.width;
  60561. screenSize.y = _this.motionBlurPostProcess.height;
  60562. effect.setVector2("screenSize", screenSize);
  60563. motionScale = scene.getEngine().getFps() / 60.0;
  60564. effect.setFloat("motionScale", motionScale);
  60565. effect.setFloat("motionStrength", _this.motionStrength);
  60566. effect.setTexture("depthSampler", _this._getDepthTexture());
  60567. };
  60568. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  60569. };
  60570. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  60571. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  60572. var renderer = this._scene.enableGeometryBufferRenderer();
  60573. return renderer.getGBuffer().textures[0];
  60574. }
  60575. return this._scene.enableDepthRenderer().getDepthMap();
  60576. };
  60577. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  60578. for (var i = 0; i < this._cameras.length; i++) {
  60579. var camera = this._cameras[i];
  60580. if (this.originalPostProcess) {
  60581. this.originalPostProcess.dispose(camera);
  60582. }
  60583. if (this.downSampleX4PostProcess) {
  60584. this.downSampleX4PostProcess.dispose(camera);
  60585. }
  60586. if (this.brightPassPostProcess) {
  60587. this.brightPassPostProcess.dispose(camera);
  60588. }
  60589. if (this.textureAdderPostProcess) {
  60590. this.textureAdderPostProcess.dispose(camera);
  60591. }
  60592. if (this.textureAdderFinalPostProcess) {
  60593. this.textureAdderFinalPostProcess.dispose(camera);
  60594. }
  60595. if (this.volumetricLightPostProcess) {
  60596. this.volumetricLightPostProcess.dispose(camera);
  60597. }
  60598. if (this.volumetricLightSmoothXPostProcess) {
  60599. this.volumetricLightSmoothXPostProcess.dispose(camera);
  60600. }
  60601. if (this.volumetricLightSmoothYPostProcess) {
  60602. this.volumetricLightSmoothYPostProcess.dispose(camera);
  60603. }
  60604. if (this.volumetricLightMergePostProces) {
  60605. this.volumetricLightMergePostProces.dispose(camera);
  60606. }
  60607. if (this.volumetricLightFinalPostProcess) {
  60608. this.volumetricLightFinalPostProcess.dispose(camera);
  60609. }
  60610. if (this.lensFlarePostProcess) {
  60611. this.lensFlarePostProcess.dispose(camera);
  60612. }
  60613. if (this.lensFlareComposePostProcess) {
  60614. this.lensFlareComposePostProcess.dispose(camera);
  60615. }
  60616. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  60617. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  60618. }
  60619. if (this.luminancePostProcess) {
  60620. this.luminancePostProcess.dispose(camera);
  60621. }
  60622. if (this.hdrPostProcess) {
  60623. this.hdrPostProcess.dispose(camera);
  60624. }
  60625. if (this.hdrFinalPostProcess) {
  60626. this.hdrFinalPostProcess.dispose(camera);
  60627. }
  60628. if (this.depthOfFieldPostProcess) {
  60629. this.depthOfFieldPostProcess.dispose(camera);
  60630. }
  60631. if (this.motionBlurPostProcess) {
  60632. this.motionBlurPostProcess.dispose(camera);
  60633. }
  60634. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  60635. this.blurHPostProcesses[j].dispose(camera);
  60636. }
  60637. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  60638. this.blurVPostProcesses[j].dispose(camera);
  60639. }
  60640. }
  60641. this.originalPostProcess = null;
  60642. this.downSampleX4PostProcess = null;
  60643. this.brightPassPostProcess = null;
  60644. this.textureAdderPostProcess = null;
  60645. this.textureAdderFinalPostProcess = null;
  60646. this.volumetricLightPostProcess = null;
  60647. this.volumetricLightSmoothXPostProcess = null;
  60648. this.volumetricLightSmoothYPostProcess = null;
  60649. this.volumetricLightMergePostProces = null;
  60650. this.volumetricLightFinalPostProcess = null;
  60651. this.lensFlarePostProcess = null;
  60652. this.lensFlareComposePostProcess = null;
  60653. this.luminancePostProcess = null;
  60654. this.hdrPostProcess = null;
  60655. this.hdrFinalPostProcess = null;
  60656. this.depthOfFieldPostProcess = null;
  60657. this.motionBlurPostProcess = null;
  60658. this.luminanceDownSamplePostProcesses = [];
  60659. this.blurHPostProcesses = [];
  60660. this.blurVPostProcesses = [];
  60661. };
  60662. // Dispose
  60663. StandardRenderingPipeline.prototype.dispose = function () {
  60664. this._disposePostProcesses();
  60665. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  60666. _super.prototype.dispose.call(this);
  60667. };
  60668. // Serialize rendering pipeline
  60669. StandardRenderingPipeline.prototype.serialize = function () {
  60670. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  60671. serializationObject.customType = "StandardRenderingPipeline";
  60672. return serializationObject;
  60673. };
  60674. /**
  60675. * Static members
  60676. */
  60677. // Parse serialized pipeline
  60678. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  60679. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  60680. };
  60681. // Luminance steps
  60682. StandardRenderingPipeline.LuminanceSteps = 6;
  60683. __decorate([
  60684. BABYLON.serialize()
  60685. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  60686. __decorate([
  60687. BABYLON.serialize()
  60688. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  60689. __decorate([
  60690. BABYLON.serialize()
  60691. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  60692. __decorate([
  60693. BABYLON.serialize()
  60694. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  60695. __decorate([
  60696. BABYLON.serializeAsTexture("lensTexture")
  60697. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  60698. __decorate([
  60699. BABYLON.serialize()
  60700. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  60701. __decorate([
  60702. BABYLON.serialize()
  60703. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  60704. __decorate([
  60705. BABYLON.serialize()
  60706. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  60707. __decorate([
  60708. BABYLON.serialize()
  60709. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  60710. __decorate([
  60711. BABYLON.serialize()
  60712. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  60713. __decorate([
  60714. BABYLON.serialize()
  60715. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  60716. __decorate([
  60717. BABYLON.serializeAsTexture("lensColorTexture")
  60718. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  60719. __decorate([
  60720. BABYLON.serialize()
  60721. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  60722. __decorate([
  60723. BABYLON.serialize()
  60724. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  60725. __decorate([
  60726. BABYLON.serialize()
  60727. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  60728. __decorate([
  60729. BABYLON.serialize()
  60730. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  60731. __decorate([
  60732. BABYLON.serializeAsTexture("lensStarTexture")
  60733. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  60734. __decorate([
  60735. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  60736. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  60737. __decorate([
  60738. BABYLON.serialize()
  60739. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  60740. __decorate([
  60741. BABYLON.serialize()
  60742. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  60743. __decorate([
  60744. BABYLON.serialize()
  60745. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  60746. __decorate([
  60747. BABYLON.serialize()
  60748. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  60749. __decorate([
  60750. BABYLON.serialize()
  60751. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  60752. __decorate([
  60753. BABYLON.serialize()
  60754. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  60755. __decorate([
  60756. BABYLON.serialize()
  60757. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  60758. __decorate([
  60759. BABYLON.serialize()
  60760. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  60761. __decorate([
  60762. BABYLON.serialize()
  60763. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  60764. __decorate([
  60765. BABYLON.serialize()
  60766. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  60767. __decorate([
  60768. BABYLON.serialize()
  60769. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  60770. __decorate([
  60771. BABYLON.serialize()
  60772. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  60773. return StandardRenderingPipeline;
  60774. }(BABYLON.PostProcessRenderPipeline));
  60775. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  60776. })(BABYLON || (BABYLON = {}));
  60777. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  60778. var BABYLON;
  60779. (function (BABYLON) {
  60780. var FxaaPostProcess = /** @class */ (function (_super) {
  60781. __extends(FxaaPostProcess, _super);
  60782. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  60783. if (camera === void 0) { camera = null; }
  60784. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  60785. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  60786. _this.onApplyObservable.add(function (effect) {
  60787. var texelSize = _this.texelSize;
  60788. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  60789. });
  60790. return _this;
  60791. }
  60792. return FxaaPostProcess;
  60793. }(BABYLON.PostProcess));
  60794. BABYLON.FxaaPostProcess = FxaaPostProcess;
  60795. })(BABYLON || (BABYLON = {}));
  60796. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  60797. var BABYLON;
  60798. (function (BABYLON) {
  60799. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  60800. __extends(DefaultRenderingPipeline, _super);
  60801. /**
  60802. * @constructor
  60803. * @param {string} name - The rendering pipeline name
  60804. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  60805. * @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)
  60806. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  60807. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  60808. */
  60809. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  60810. if (automaticBuild === void 0) { automaticBuild = true; }
  60811. var _this = _super.call(this, scene.getEngine(), name) || this;
  60812. _this.PassPostProcessId = "PassPostProcessEffect";
  60813. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  60814. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  60815. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  60816. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  60817. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  60818. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  60819. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  60820. // IAnimatable
  60821. _this.animations = [];
  60822. // Values
  60823. _this._bloomEnabled = false;
  60824. _this._fxaaEnabled = false;
  60825. _this._imageProcessingEnabled = true;
  60826. _this._bloomScale = 0.6;
  60827. _this._buildAllowed = true;
  60828. /**
  60829. * Specifies the size of the bloom blur kernel, relative to the final output size
  60830. */
  60831. _this.bloomKernel = 64;
  60832. /**
  60833. * Specifies the weight of the bloom in the final rendering
  60834. */
  60835. _this._bloomWeight = 0.15;
  60836. _this._cameras = cameras || [];
  60837. _this._buildAllowed = automaticBuild;
  60838. // Initialize
  60839. _this._scene = scene;
  60840. var caps = _this._scene.getEngine().getCaps();
  60841. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  60842. // Misc
  60843. if (_this._hdr) {
  60844. if (caps.textureHalfFloatRender) {
  60845. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  60846. }
  60847. else if (caps.textureFloatRender) {
  60848. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  60849. }
  60850. }
  60851. else {
  60852. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  60853. }
  60854. // Attach
  60855. scene.postProcessRenderPipelineManager.addPipeline(_this);
  60856. _this._buildPipeline();
  60857. return _this;
  60858. }
  60859. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  60860. get: function () {
  60861. return this._bloomWeight;
  60862. },
  60863. set: function (value) {
  60864. if (this._bloomWeight === value) {
  60865. return;
  60866. }
  60867. this._bloomWeight = value;
  60868. if (this._hdr && this.copyBack) {
  60869. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  60870. }
  60871. },
  60872. enumerable: true,
  60873. configurable: true
  60874. });
  60875. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  60876. get: function () {
  60877. return this._bloomScale;
  60878. },
  60879. set: function (value) {
  60880. if (this._bloomScale === value) {
  60881. return;
  60882. }
  60883. this._bloomScale = value;
  60884. this._buildPipeline();
  60885. },
  60886. enumerable: true,
  60887. configurable: true
  60888. });
  60889. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  60890. get: function () {
  60891. return this._bloomEnabled;
  60892. },
  60893. set: function (enabled) {
  60894. if (this._bloomEnabled === enabled) {
  60895. return;
  60896. }
  60897. this._bloomEnabled = enabled;
  60898. this._buildPipeline();
  60899. },
  60900. enumerable: true,
  60901. configurable: true
  60902. });
  60903. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  60904. get: function () {
  60905. return this._fxaaEnabled;
  60906. },
  60907. set: function (enabled) {
  60908. if (this._fxaaEnabled === enabled) {
  60909. return;
  60910. }
  60911. this._fxaaEnabled = enabled;
  60912. this._buildPipeline();
  60913. },
  60914. enumerable: true,
  60915. configurable: true
  60916. });
  60917. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  60918. get: function () {
  60919. return this._imageProcessingEnabled;
  60920. },
  60921. set: function (enabled) {
  60922. if (this._imageProcessingEnabled === enabled) {
  60923. return;
  60924. }
  60925. this._imageProcessingEnabled = enabled;
  60926. this._buildPipeline();
  60927. },
  60928. enumerable: true,
  60929. configurable: true
  60930. });
  60931. /**
  60932. * Force the compilation of the entire pipeline.
  60933. */
  60934. DefaultRenderingPipeline.prototype.prepare = function () {
  60935. var previousState = this._buildAllowed;
  60936. this._buildAllowed = true;
  60937. this._buildPipeline();
  60938. this._buildAllowed = previousState;
  60939. };
  60940. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  60941. var _this = this;
  60942. if (!this._buildAllowed) {
  60943. return;
  60944. }
  60945. var engine = this._scene.getEngine();
  60946. this._disposePostProcesses();
  60947. this._reset();
  60948. if (this.bloomEnabled) {
  60949. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  60950. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  60951. if (!this._hdr) {
  60952. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  60953. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  60954. this.highlights.autoClear = false;
  60955. this.highlights.alwaysForcePOT = true;
  60956. }
  60957. 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);
  60958. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  60959. this.blurX.alwaysForcePOT = true;
  60960. this.blurX.autoClear = false;
  60961. this.blurX.onActivateObservable.add(function () {
  60962. var dw = _this.blurX.width / engine.getRenderWidth(true);
  60963. _this.blurX.kernel = _this.bloomKernel * dw;
  60964. });
  60965. 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);
  60966. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  60967. this.blurY.alwaysForcePOT = true;
  60968. this.blurY.autoClear = false;
  60969. this.blurY.onActivateObservable.add(function () {
  60970. var dh = _this.blurY.height / engine.getRenderHeight(true);
  60971. _this.blurY.kernel = _this.bloomKernel * dh;
  60972. });
  60973. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  60974. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  60975. this.copyBack.alwaysForcePOT = true;
  60976. if (this._hdr) {
  60977. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  60978. var w = this.bloomWeight;
  60979. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  60980. }
  60981. else {
  60982. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  60983. }
  60984. this.copyBack.autoClear = false;
  60985. }
  60986. if (this._imageProcessingEnabled) {
  60987. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  60988. if (this._hdr) {
  60989. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  60990. }
  60991. else {
  60992. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  60993. }
  60994. }
  60995. if (this.fxaaEnabled) {
  60996. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  60997. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  60998. this.fxaa.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  60999. }
  61000. else if (this._hdr && this.imageProcessing) {
  61001. this.finalMerge = this.imageProcessing;
  61002. }
  61003. else {
  61004. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  61005. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  61006. this.finalMerge.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  61007. }
  61008. if (this.bloomEnabled) {
  61009. if (this._hdr) {
  61010. this.copyBack.shareOutputWith(this.blurX);
  61011. if (this.imageProcessing) {
  61012. this.imageProcessing.shareOutputWith(this.pass);
  61013. this.imageProcessing.autoClear = false;
  61014. }
  61015. else if (this.fxaa) {
  61016. this.fxaa.shareOutputWith(this.pass);
  61017. }
  61018. else {
  61019. this.finalMerge.shareOutputWith(this.pass);
  61020. }
  61021. }
  61022. else {
  61023. if (this.fxaa) {
  61024. this.fxaa.shareOutputWith(this.pass);
  61025. }
  61026. else {
  61027. this.finalMerge.shareOutputWith(this.pass);
  61028. }
  61029. }
  61030. }
  61031. if (this._cameras !== null) {
  61032. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  61033. }
  61034. };
  61035. DefaultRenderingPipeline.prototype._disposePostProcesses = function () {
  61036. for (var i = 0; i < this._cameras.length; i++) {
  61037. var camera = this._cameras[i];
  61038. if (this.pass) {
  61039. this.pass.dispose(camera);
  61040. }
  61041. if (this.highlights) {
  61042. this.highlights.dispose(camera);
  61043. }
  61044. if (this.blurX) {
  61045. this.blurX.dispose(camera);
  61046. }
  61047. if (this.blurY) {
  61048. this.blurY.dispose(camera);
  61049. }
  61050. if (this.copyBack) {
  61051. this.copyBack.dispose(camera);
  61052. }
  61053. if (this.imageProcessing) {
  61054. this.imageProcessing.dispose(camera);
  61055. }
  61056. if (this.fxaa) {
  61057. this.fxaa.dispose(camera);
  61058. }
  61059. if (this.finalMerge) {
  61060. this.finalMerge.dispose(camera);
  61061. }
  61062. }
  61063. this.pass = null;
  61064. this.highlights = null;
  61065. this.blurX = null;
  61066. this.blurY = null;
  61067. this.copyBack = null;
  61068. this.imageProcessing = null;
  61069. this.fxaa = null;
  61070. this.finalMerge = null;
  61071. };
  61072. // Dispose
  61073. DefaultRenderingPipeline.prototype.dispose = function () {
  61074. this._disposePostProcesses();
  61075. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  61076. _super.prototype.dispose.call(this);
  61077. };
  61078. // Serialize rendering pipeline
  61079. DefaultRenderingPipeline.prototype.serialize = function () {
  61080. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  61081. serializationObject.customType = "DefaultRenderingPipeline";
  61082. return serializationObject;
  61083. };
  61084. // Parse serialized pipeline
  61085. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  61086. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  61087. };
  61088. __decorate([
  61089. BABYLON.serialize()
  61090. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  61091. __decorate([
  61092. BABYLON.serialize()
  61093. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  61094. __decorate([
  61095. BABYLON.serialize()
  61096. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  61097. __decorate([
  61098. BABYLON.serialize()
  61099. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  61100. __decorate([
  61101. BABYLON.serialize()
  61102. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  61103. __decorate([
  61104. BABYLON.serialize()
  61105. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  61106. __decorate([
  61107. BABYLON.serialize()
  61108. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  61109. __decorate([
  61110. BABYLON.serialize()
  61111. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  61112. return DefaultRenderingPipeline;
  61113. }(BABYLON.PostProcessRenderPipeline));
  61114. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  61115. })(BABYLON || (BABYLON = {}));
  61116. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  61117. var BABYLON;
  61118. (function (BABYLON) {
  61119. var GeometryBufferRenderer = /** @class */ (function () {
  61120. function GeometryBufferRenderer(scene, ratio) {
  61121. if (ratio === void 0) { ratio = 1; }
  61122. this._enablePosition = false;
  61123. this._scene = scene;
  61124. this._ratio = ratio;
  61125. // Render target
  61126. this._createRenderTargets();
  61127. }
  61128. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  61129. set: function (meshes) {
  61130. this._multiRenderTarget.renderList = meshes;
  61131. },
  61132. enumerable: true,
  61133. configurable: true
  61134. });
  61135. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  61136. get: function () {
  61137. return this._multiRenderTarget.isSupported;
  61138. },
  61139. enumerable: true,
  61140. configurable: true
  61141. });
  61142. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  61143. get: function () {
  61144. return this._enablePosition;
  61145. },
  61146. set: function (enable) {
  61147. this._enablePosition = enable;
  61148. this.dispose();
  61149. this._createRenderTargets();
  61150. },
  61151. enumerable: true,
  61152. configurable: true
  61153. });
  61154. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  61155. var material = subMesh.getMaterial();
  61156. if (material && material.disableDepthWrite) {
  61157. return false;
  61158. }
  61159. var defines = [];
  61160. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  61161. var mesh = subMesh.getMesh();
  61162. // Alpha test
  61163. if (material && material.needAlphaTesting()) {
  61164. defines.push("#define ALPHATEST");
  61165. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  61166. attribs.push(BABYLON.VertexBuffer.UVKind);
  61167. defines.push("#define UV1");
  61168. }
  61169. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  61170. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  61171. defines.push("#define UV2");
  61172. }
  61173. }
  61174. // Buffers
  61175. if (this._enablePosition) {
  61176. defines.push("#define POSITION");
  61177. }
  61178. // Bones
  61179. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  61180. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  61181. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  61182. if (mesh.numBoneInfluencers > 4) {
  61183. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  61184. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  61185. }
  61186. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  61187. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  61188. }
  61189. else {
  61190. defines.push("#define NUM_BONE_INFLUENCERS 0");
  61191. }
  61192. // Instances
  61193. if (useInstances) {
  61194. defines.push("#define INSTANCES");
  61195. attribs.push("world0");
  61196. attribs.push("world1");
  61197. attribs.push("world2");
  61198. attribs.push("world3");
  61199. }
  61200. // Get correct effect
  61201. var join = defines.join("\n");
  61202. if (this._cachedDefines !== join) {
  61203. this._cachedDefines = join;
  61204. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  61205. }
  61206. return this._effect.isReady();
  61207. };
  61208. GeometryBufferRenderer.prototype.getGBuffer = function () {
  61209. return this._multiRenderTarget;
  61210. };
  61211. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  61212. get: function () {
  61213. return this._multiRenderTarget.samples;
  61214. },
  61215. set: function (value) {
  61216. this._multiRenderTarget.samples = value;
  61217. },
  61218. enumerable: true,
  61219. configurable: true
  61220. });
  61221. // Methods
  61222. GeometryBufferRenderer.prototype.dispose = function () {
  61223. this.getGBuffer().dispose();
  61224. };
  61225. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  61226. var _this = this;
  61227. var engine = this._scene.getEngine();
  61228. var count = this._enablePosition ? 3 : 2;
  61229. this._multiRenderTarget = new BABYLON.MultiRenderTarget("gBuffer", { width: engine.getRenderWidth() * this._ratio, height: engine.getRenderHeight() * this._ratio }, count, this._scene, { generateMipMaps: false, generateDepthTexture: true });
  61230. if (!this.isSupported) {
  61231. return;
  61232. }
  61233. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61234. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61235. this._multiRenderTarget.refreshRate = 1;
  61236. this._multiRenderTarget.renderParticles = false;
  61237. this._multiRenderTarget.renderList = null;
  61238. // set default depth value to 1.0 (far away)
  61239. this._multiRenderTarget.onClearObservable.add(function (engine) {
  61240. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  61241. });
  61242. // Custom render function
  61243. var renderSubMesh = function (subMesh) {
  61244. var mesh = subMesh.getRenderingMesh();
  61245. var scene = _this._scene;
  61246. var engine = scene.getEngine();
  61247. var material = subMesh.getMaterial();
  61248. if (!material) {
  61249. return;
  61250. }
  61251. // Culling
  61252. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  61253. // Managing instances
  61254. var batch = mesh._getInstancesRenderList(subMesh._id);
  61255. if (batch.mustReturn) {
  61256. return;
  61257. }
  61258. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  61259. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  61260. engine.enableEffect(_this._effect);
  61261. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  61262. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  61263. _this._effect.setMatrix("view", scene.getViewMatrix());
  61264. // Alpha test
  61265. if (material && material.needAlphaTesting()) {
  61266. var alphaTexture = material.getAlphaTestTexture();
  61267. if (alphaTexture) {
  61268. _this._effect.setTexture("diffuseSampler", alphaTexture);
  61269. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  61270. }
  61271. }
  61272. // Bones
  61273. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  61274. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  61275. }
  61276. // Draw
  61277. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  61278. }
  61279. };
  61280. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  61281. var index;
  61282. if (depthOnlySubMeshes.length) {
  61283. engine.setColorWrite(false);
  61284. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  61285. renderSubMesh(depthOnlySubMeshes.data[index]);
  61286. }
  61287. engine.setColorWrite(true);
  61288. }
  61289. for (index = 0; index < opaqueSubMeshes.length; index++) {
  61290. renderSubMesh(opaqueSubMeshes.data[index]);
  61291. }
  61292. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  61293. renderSubMesh(alphaTestSubMeshes.data[index]);
  61294. }
  61295. };
  61296. };
  61297. return GeometryBufferRenderer;
  61298. }());
  61299. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  61300. })(BABYLON || (BABYLON = {}));
  61301. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  61302. var BABYLON;
  61303. (function (BABYLON) {
  61304. var RefractionPostProcess = /** @class */ (function (_super) {
  61305. __extends(RefractionPostProcess, _super);
  61306. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  61307. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  61308. _this.color = color;
  61309. _this.depth = depth;
  61310. _this.colorLevel = colorLevel;
  61311. _this.onActivateObservable.add(function (cam) {
  61312. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  61313. });
  61314. _this.onApplyObservable.add(function (effect) {
  61315. effect.setColor3("baseColor", _this.color);
  61316. effect.setFloat("depth", _this.depth);
  61317. effect.setFloat("colorLevel", _this.colorLevel);
  61318. effect.setTexture("refractionSampler", _this._refRexture);
  61319. });
  61320. return _this;
  61321. }
  61322. // Methods
  61323. RefractionPostProcess.prototype.dispose = function (camera) {
  61324. if (this._refRexture) {
  61325. this._refRexture.dispose();
  61326. }
  61327. _super.prototype.dispose.call(this, camera);
  61328. };
  61329. return RefractionPostProcess;
  61330. }(BABYLON.PostProcess));
  61331. BABYLON.RefractionPostProcess = RefractionPostProcess;
  61332. })(BABYLON || (BABYLON = {}));
  61333. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  61334. var BABYLON;
  61335. (function (BABYLON) {
  61336. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  61337. __extends(BlackAndWhitePostProcess, _super);
  61338. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  61339. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  61340. _this.degree = 1;
  61341. _this.onApplyObservable.add(function (effect) {
  61342. effect.setFloat("degree", _this.degree);
  61343. });
  61344. return _this;
  61345. }
  61346. return BlackAndWhitePostProcess;
  61347. }(BABYLON.PostProcess));
  61348. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  61349. })(BABYLON || (BABYLON = {}));
  61350. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  61351. var BABYLON;
  61352. (function (BABYLON) {
  61353. var ConvolutionPostProcess = /** @class */ (function (_super) {
  61354. __extends(ConvolutionPostProcess, _super);
  61355. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  61356. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable) || this;
  61357. _this.kernel = kernel;
  61358. _this.onApply = function (effect) {
  61359. effect.setFloat2("screenSize", _this.width, _this.height);
  61360. effect.setArray("kernel", _this.kernel);
  61361. };
  61362. return _this;
  61363. }
  61364. // Statics
  61365. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  61366. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  61367. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  61368. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  61369. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  61370. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  61371. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  61372. return ConvolutionPostProcess;
  61373. }(BABYLON.PostProcess));
  61374. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  61375. })(BABYLON || (BABYLON = {}));
  61376. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  61377. var BABYLON;
  61378. (function (BABYLON) {
  61379. var FilterPostProcess = /** @class */ (function (_super) {
  61380. __extends(FilterPostProcess, _super);
  61381. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  61382. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  61383. _this.kernelMatrix = kernelMatrix;
  61384. _this.onApply = function (effect) {
  61385. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  61386. };
  61387. return _this;
  61388. }
  61389. return FilterPostProcess;
  61390. }(BABYLON.PostProcess));
  61391. BABYLON.FilterPostProcess = FilterPostProcess;
  61392. })(BABYLON || (BABYLON = {}));
  61393. //# sourceMappingURL=babylon.filterPostProcess.js.map
  61394. var BABYLON;
  61395. (function (BABYLON) {
  61396. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  61397. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  61398. __extends(VolumetricLightScatteringPostProcess, _super);
  61399. /**
  61400. * @constructor
  61401. * @param {string} name - The post-process name
  61402. * @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)
  61403. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  61404. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  61405. * @param {number} samples - The post-process quality, default 100
  61406. * @param {number} samplingMode - The post-process filtering mode
  61407. * @param {BABYLON.Engine} engine - The babylon engine
  61408. * @param {boolean} reusable - If the post-process is reusable
  61409. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  61410. */
  61411. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  61412. if (samples === void 0) { samples = 100; }
  61413. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  61414. 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;
  61415. _this._screenCoordinates = BABYLON.Vector2.Zero();
  61416. /**
  61417. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  61418. * @type {Vector3}
  61419. */
  61420. _this.customMeshPosition = BABYLON.Vector3.Zero();
  61421. /**
  61422. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  61423. * @type {boolean}
  61424. */
  61425. _this.useCustomMeshPosition = false;
  61426. /**
  61427. * If the post-process should inverse the light scattering direction
  61428. * @type {boolean}
  61429. */
  61430. _this.invert = true;
  61431. /**
  61432. * Array containing the excluded meshes not rendered in the internal pass
  61433. */
  61434. _this.excludedMeshes = new Array();
  61435. /**
  61436. * Controls the overall intensity of the post-process
  61437. * @type {number}
  61438. */
  61439. _this.exposure = 0.3;
  61440. /**
  61441. * Dissipates each sample's contribution in range [0, 1]
  61442. * @type {number}
  61443. */
  61444. _this.decay = 0.96815;
  61445. /**
  61446. * Controls the overall intensity of each sample
  61447. * @type {number}
  61448. */
  61449. _this.weight = 0.58767;
  61450. /**
  61451. * Controls the density of each sample
  61452. * @type {number}
  61453. */
  61454. _this.density = 0.926;
  61455. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  61456. engine = scene.getEngine();
  61457. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  61458. // Configure mesh
  61459. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  61460. // Configure
  61461. _this._createPass(scene, ratio.passRatio || ratio);
  61462. _this.onActivate = function (camera) {
  61463. if (!_this.isSupported) {
  61464. _this.dispose(camera);
  61465. }
  61466. _this.onActivate = null;
  61467. };
  61468. _this.onApplyObservable.add(function (effect) {
  61469. _this._updateMeshScreenCoordinates(scene);
  61470. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  61471. effect.setFloat("exposure", _this.exposure);
  61472. effect.setFloat("decay", _this.decay);
  61473. effect.setFloat("weight", _this.weight);
  61474. effect.setFloat("density", _this.density);
  61475. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  61476. });
  61477. return _this;
  61478. }
  61479. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  61480. get: function () {
  61481. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  61482. return false;
  61483. },
  61484. set: function (useDiffuseColor) {
  61485. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  61486. },
  61487. enumerable: true,
  61488. configurable: true
  61489. });
  61490. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  61491. return "VolumetricLightScatteringPostProcess";
  61492. };
  61493. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  61494. var mesh = subMesh.getMesh();
  61495. // Render this.mesh as default
  61496. if (mesh === this.mesh && mesh.material) {
  61497. return mesh.material.isReady(mesh);
  61498. }
  61499. var defines = [];
  61500. var attribs = [BABYLON.VertexBuffer.PositionKind];
  61501. var material = subMesh.getMaterial();
  61502. // Alpha test
  61503. if (material) {
  61504. if (material.needAlphaTesting()) {
  61505. defines.push("#define ALPHATEST");
  61506. }
  61507. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  61508. attribs.push(BABYLON.VertexBuffer.UVKind);
  61509. defines.push("#define UV1");
  61510. }
  61511. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  61512. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  61513. defines.push("#define UV2");
  61514. }
  61515. }
  61516. // Bones
  61517. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  61518. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  61519. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  61520. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  61521. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  61522. }
  61523. else {
  61524. defines.push("#define NUM_BONE_INFLUENCERS 0");
  61525. }
  61526. // Instances
  61527. if (useInstances) {
  61528. defines.push("#define INSTANCES");
  61529. attribs.push("world0");
  61530. attribs.push("world1");
  61531. attribs.push("world2");
  61532. attribs.push("world3");
  61533. }
  61534. // Get correct effect
  61535. var join = defines.join("\n");
  61536. if (this._cachedDefines !== join) {
  61537. this._cachedDefines = join;
  61538. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  61539. }
  61540. return this._volumetricLightScatteringPass.isReady();
  61541. };
  61542. /**
  61543. * Sets the new light position for light scattering effect
  61544. * @param {BABYLON.Vector3} The new custom light position
  61545. */
  61546. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  61547. this.customMeshPosition = position;
  61548. };
  61549. /**
  61550. * Returns the light position for light scattering effect
  61551. * @return {BABYLON.Vector3} The custom light position
  61552. */
  61553. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  61554. return this.customMeshPosition;
  61555. };
  61556. /**
  61557. * Disposes the internal assets and detaches the post-process from the camera
  61558. */
  61559. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  61560. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  61561. if (rttIndex !== -1) {
  61562. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  61563. }
  61564. this._volumetricLightScatteringRTT.dispose();
  61565. _super.prototype.dispose.call(this, camera);
  61566. };
  61567. /**
  61568. * Returns the render target texture used by the post-process
  61569. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  61570. */
  61571. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  61572. return this._volumetricLightScatteringRTT;
  61573. };
  61574. // Private methods
  61575. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  61576. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  61577. return true;
  61578. }
  61579. return false;
  61580. };
  61581. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  61582. var _this = this;
  61583. var engine = scene.getEngine();
  61584. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  61585. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61586. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61587. this._volumetricLightScatteringRTT.renderList = null;
  61588. this._volumetricLightScatteringRTT.renderParticles = false;
  61589. var camera = this.getCamera();
  61590. if (camera) {
  61591. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  61592. }
  61593. else {
  61594. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  61595. }
  61596. // Custom render function for submeshes
  61597. var renderSubMesh = function (subMesh) {
  61598. var mesh = subMesh.getRenderingMesh();
  61599. if (_this._meshExcluded(mesh)) {
  61600. return;
  61601. }
  61602. var material = subMesh.getMaterial();
  61603. if (!material) {
  61604. return;
  61605. }
  61606. var scene = mesh.getScene();
  61607. var engine = scene.getEngine();
  61608. // Culling
  61609. engine.setState(material.backFaceCulling);
  61610. // Managing instances
  61611. var batch = mesh._getInstancesRenderList(subMesh._id);
  61612. if (batch.mustReturn) {
  61613. return;
  61614. }
  61615. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  61616. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  61617. var effect = _this._volumetricLightScatteringPass;
  61618. if (mesh === _this.mesh) {
  61619. if (subMesh.effect) {
  61620. effect = subMesh.effect;
  61621. }
  61622. else {
  61623. effect = material.getEffect();
  61624. }
  61625. }
  61626. engine.enableEffect(effect);
  61627. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  61628. if (mesh === _this.mesh) {
  61629. material.bind(mesh.getWorldMatrix(), mesh);
  61630. }
  61631. else {
  61632. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  61633. // Alpha test
  61634. if (material && material.needAlphaTesting()) {
  61635. var alphaTexture = material.getAlphaTestTexture();
  61636. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  61637. if (alphaTexture) {
  61638. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  61639. }
  61640. }
  61641. // Bones
  61642. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  61643. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  61644. }
  61645. }
  61646. // Draw
  61647. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  61648. }
  61649. };
  61650. // Render target texture callbacks
  61651. var savedSceneClearColor;
  61652. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  61653. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  61654. savedSceneClearColor = scene.clearColor;
  61655. scene.clearColor = sceneClearColor;
  61656. });
  61657. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  61658. scene.clearColor = savedSceneClearColor;
  61659. });
  61660. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  61661. var engine = scene.getEngine();
  61662. var index;
  61663. if (depthOnlySubMeshes.length) {
  61664. engine.setColorWrite(false);
  61665. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  61666. renderSubMesh(depthOnlySubMeshes.data[index]);
  61667. }
  61668. engine.setColorWrite(true);
  61669. }
  61670. for (index = 0; index < opaqueSubMeshes.length; index++) {
  61671. renderSubMesh(opaqueSubMeshes.data[index]);
  61672. }
  61673. engine.setAlphaTesting(true);
  61674. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  61675. renderSubMesh(alphaTestSubMeshes.data[index]);
  61676. }
  61677. engine.setAlphaTesting(false);
  61678. if (transparentSubMeshes.length) {
  61679. // Sort sub meshes
  61680. for (index = 0; index < transparentSubMeshes.length; index++) {
  61681. var submesh = transparentSubMeshes.data[index];
  61682. var boundingInfo = submesh.getBoundingInfo();
  61683. if (boundingInfo && scene.activeCamera) {
  61684. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  61685. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  61686. }
  61687. }
  61688. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  61689. sortedArray.sort(function (a, b) {
  61690. // Alpha index first
  61691. if (a._alphaIndex > b._alphaIndex) {
  61692. return 1;
  61693. }
  61694. if (a._alphaIndex < b._alphaIndex) {
  61695. return -1;
  61696. }
  61697. // Then distance to camera
  61698. if (a._distanceToCamera < b._distanceToCamera) {
  61699. return 1;
  61700. }
  61701. if (a._distanceToCamera > b._distanceToCamera) {
  61702. return -1;
  61703. }
  61704. return 0;
  61705. });
  61706. // Render sub meshes
  61707. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  61708. for (index = 0; index < sortedArray.length; index++) {
  61709. renderSubMesh(sortedArray[index]);
  61710. }
  61711. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  61712. }
  61713. };
  61714. };
  61715. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  61716. var transform = scene.getTransformMatrix();
  61717. var meshPosition;
  61718. if (this.useCustomMeshPosition) {
  61719. meshPosition = this.customMeshPosition;
  61720. }
  61721. else if (this.attachedNode) {
  61722. meshPosition = this.attachedNode.position;
  61723. }
  61724. else {
  61725. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  61726. }
  61727. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  61728. this._screenCoordinates.x = pos.x / this._viewPort.width;
  61729. this._screenCoordinates.y = pos.y / this._viewPort.height;
  61730. if (this.invert)
  61731. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  61732. };
  61733. // Static methods
  61734. /**
  61735. * Creates a default mesh for the Volumeric Light Scattering post-process
  61736. * @param {string} The mesh name
  61737. * @param {BABYLON.Scene} The scene where to create the mesh
  61738. * @return {BABYLON.Mesh} the default mesh
  61739. */
  61740. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  61741. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  61742. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  61743. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  61744. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  61745. mesh.material = material;
  61746. return mesh;
  61747. };
  61748. __decorate([
  61749. BABYLON.serializeAsVector3()
  61750. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  61751. __decorate([
  61752. BABYLON.serialize()
  61753. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  61754. __decorate([
  61755. BABYLON.serialize()
  61756. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  61757. __decorate([
  61758. BABYLON.serializeAsMeshReference()
  61759. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  61760. __decorate([
  61761. BABYLON.serialize()
  61762. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  61763. __decorate([
  61764. BABYLON.serialize()
  61765. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  61766. __decorate([
  61767. BABYLON.serialize()
  61768. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  61769. __decorate([
  61770. BABYLON.serialize()
  61771. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  61772. __decorate([
  61773. BABYLON.serialize()
  61774. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  61775. return VolumetricLightScatteringPostProcess;
  61776. }(BABYLON.PostProcess));
  61777. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  61778. })(BABYLON || (BABYLON = {}));
  61779. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  61780. //
  61781. // This post-process allows the modification of rendered colors by using
  61782. // a 'look-up table' (LUT). This effect is also called Color Grading.
  61783. //
  61784. // The object needs to be provided an url to a texture containing the color
  61785. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  61786. // Use an image editing software to tweak the LUT to match your needs.
  61787. //
  61788. // For an example of a color LUT, see here:
  61789. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  61790. // For explanations on color grading, see here:
  61791. // http://udn.epicgames.com/Three/ColorGrading.html
  61792. //
  61793. var BABYLON;
  61794. (function (BABYLON) {
  61795. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  61796. __extends(ColorCorrectionPostProcess, _super);
  61797. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  61798. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  61799. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  61800. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  61801. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61802. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61803. _this.onApply = function (effect) {
  61804. effect.setTexture("colorTable", _this._colorTableTexture);
  61805. };
  61806. return _this;
  61807. }
  61808. return ColorCorrectionPostProcess;
  61809. }(BABYLON.PostProcess));
  61810. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  61811. })(BABYLON || (BABYLON = {}));
  61812. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  61813. var BABYLON;
  61814. (function (BABYLON) {
  61815. var TonemappingOperator;
  61816. (function (TonemappingOperator) {
  61817. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  61818. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  61819. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  61820. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  61821. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  61822. ;
  61823. var TonemapPostProcess = /** @class */ (function (_super) {
  61824. __extends(TonemapPostProcess, _super);
  61825. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  61826. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  61827. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  61828. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  61829. _this._operator = _operator;
  61830. _this.exposureAdjustment = exposureAdjustment;
  61831. var defines = "#define ";
  61832. if (_this._operator === TonemappingOperator.Hable)
  61833. defines += "HABLE_TONEMAPPING";
  61834. else if (_this._operator === TonemappingOperator.Reinhard)
  61835. defines += "REINHARD_TONEMAPPING";
  61836. else if (_this._operator === TonemappingOperator.HejiDawson)
  61837. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  61838. else if (_this._operator === TonemappingOperator.Photographic)
  61839. defines += "PHOTOGRAPHIC_TONEMAPPING";
  61840. //sadly a second call to create the effect.
  61841. _this.updateEffect(defines);
  61842. _this.onApply = function (effect) {
  61843. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  61844. };
  61845. return _this;
  61846. }
  61847. return TonemapPostProcess;
  61848. }(BABYLON.PostProcess));
  61849. BABYLON.TonemapPostProcess = TonemapPostProcess;
  61850. })(BABYLON || (BABYLON = {}));
  61851. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  61852. var BABYLON;
  61853. (function (BABYLON) {
  61854. var DisplayPassPostProcess = /** @class */ (function (_super) {
  61855. __extends(DisplayPassPostProcess, _super);
  61856. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  61857. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  61858. }
  61859. return DisplayPassPostProcess;
  61860. }(BABYLON.PostProcess));
  61861. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  61862. })(BABYLON || (BABYLON = {}));
  61863. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  61864. var BABYLON;
  61865. (function (BABYLON) {
  61866. var HighlightsPostProcess = /** @class */ (function (_super) {
  61867. __extends(HighlightsPostProcess, _super);
  61868. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  61869. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  61870. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  61871. }
  61872. return HighlightsPostProcess;
  61873. }(BABYLON.PostProcess));
  61874. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  61875. })(BABYLON || (BABYLON = {}));
  61876. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  61877. var BABYLON;
  61878. (function (BABYLON) {
  61879. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  61880. __extends(ImageProcessingPostProcess, _super);
  61881. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  61882. if (camera === void 0) { camera = null; }
  61883. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  61884. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  61885. _this._fromLinearSpace = true;
  61886. /**
  61887. * Defines cache preventing GC.
  61888. */
  61889. _this._defines = {
  61890. IMAGEPROCESSING: false,
  61891. VIGNETTE: false,
  61892. VIGNETTEBLENDMODEMULTIPLY: false,
  61893. VIGNETTEBLENDMODEOPAQUE: false,
  61894. TONEMAPPING: false,
  61895. CONTRAST: false,
  61896. COLORCURVES: false,
  61897. COLORGRADING: false,
  61898. COLORGRADING3D: false,
  61899. FROMLINEARSPACE: false,
  61900. SAMPLER3DGREENDEPTH: false,
  61901. SAMPLER3DBGRMAP: false,
  61902. IMAGEPROCESSINGPOSTPROCESS: false,
  61903. EXPOSURE: false,
  61904. };
  61905. // Setup the configuration as forced by the constructor. This would then not force the
  61906. // scene materials output in linear space and let untouched the default forward pass.
  61907. if (imageProcessingConfiguration) {
  61908. imageProcessingConfiguration.applyByPostProcess = true;
  61909. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  61910. // This will cause the shader to be compiled
  61911. _this.fromLinearSpace = false;
  61912. }
  61913. else {
  61914. _this._attachImageProcessingConfiguration(null, true);
  61915. _this.imageProcessingConfiguration.applyByPostProcess = true;
  61916. }
  61917. _this.onApply = function (effect) {
  61918. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  61919. };
  61920. return _this;
  61921. }
  61922. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  61923. /**
  61924. * Gets the image processing configuration used either in this material.
  61925. */
  61926. get: function () {
  61927. return this._imageProcessingConfiguration;
  61928. },
  61929. /**
  61930. * Sets the Default image processing configuration used either in the this material.
  61931. *
  61932. * If sets to null, the scene one is in use.
  61933. */
  61934. set: function (value) {
  61935. this._attachImageProcessingConfiguration(value);
  61936. },
  61937. enumerable: true,
  61938. configurable: true
  61939. });
  61940. /**
  61941. * Attaches a new image processing configuration to the PBR Material.
  61942. * @param configuration
  61943. */
  61944. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  61945. var _this = this;
  61946. if (doNotBuild === void 0) { doNotBuild = false; }
  61947. if (configuration === this._imageProcessingConfiguration) {
  61948. return;
  61949. }
  61950. // Detaches observer.
  61951. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  61952. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  61953. }
  61954. // Pick the scene configuration if needed.
  61955. if (!configuration) {
  61956. var scene = null;
  61957. var engine = this.getEngine();
  61958. var camera = this.getCamera();
  61959. if (camera) {
  61960. scene = camera.getScene();
  61961. }
  61962. else if (engine && engine.scenes) {
  61963. var scenes = engine.scenes;
  61964. scene = scenes[scenes.length - 1];
  61965. }
  61966. else {
  61967. scene = BABYLON.Engine.LastCreatedScene;
  61968. }
  61969. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  61970. }
  61971. else {
  61972. this._imageProcessingConfiguration = configuration;
  61973. }
  61974. // Attaches observer.
  61975. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  61976. _this._updateParameters();
  61977. });
  61978. // Ensure the effect will be rebuilt.
  61979. if (!doNotBuild) {
  61980. this._updateParameters();
  61981. }
  61982. };
  61983. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  61984. /**
  61985. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  61986. */
  61987. get: function () {
  61988. return this.imageProcessingConfiguration.colorCurves;
  61989. },
  61990. /**
  61991. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  61992. */
  61993. set: function (value) {
  61994. this.imageProcessingConfiguration.colorCurves = value;
  61995. },
  61996. enumerable: true,
  61997. configurable: true
  61998. });
  61999. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  62000. /**
  62001. * Gets wether the color curves effect is enabled.
  62002. */
  62003. get: function () {
  62004. return this.imageProcessingConfiguration.colorCurvesEnabled;
  62005. },
  62006. /**
  62007. * Sets wether the color curves effect is enabled.
  62008. */
  62009. set: function (value) {
  62010. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  62011. },
  62012. enumerable: true,
  62013. configurable: true
  62014. });
  62015. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  62016. /**
  62017. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  62018. */
  62019. get: function () {
  62020. return this.imageProcessingConfiguration.colorGradingTexture;
  62021. },
  62022. /**
  62023. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  62024. */
  62025. set: function (value) {
  62026. this.imageProcessingConfiguration.colorGradingTexture = value;
  62027. },
  62028. enumerable: true,
  62029. configurable: true
  62030. });
  62031. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  62032. /**
  62033. * Gets wether the color grading effect is enabled.
  62034. */
  62035. get: function () {
  62036. return this.imageProcessingConfiguration.colorGradingEnabled;
  62037. },
  62038. /**
  62039. * Gets wether the color grading effect is enabled.
  62040. */
  62041. set: function (value) {
  62042. this.imageProcessingConfiguration.colorGradingEnabled = value;
  62043. },
  62044. enumerable: true,
  62045. configurable: true
  62046. });
  62047. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  62048. /**
  62049. * Gets exposure used in the effect.
  62050. */
  62051. get: function () {
  62052. return this.imageProcessingConfiguration.exposure;
  62053. },
  62054. /**
  62055. * Sets exposure used in the effect.
  62056. */
  62057. set: function (value) {
  62058. this.imageProcessingConfiguration.exposure = value;
  62059. },
  62060. enumerable: true,
  62061. configurable: true
  62062. });
  62063. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  62064. /**
  62065. * Gets wether tonemapping is enabled or not.
  62066. */
  62067. get: function () {
  62068. return this._imageProcessingConfiguration.toneMappingEnabled;
  62069. },
  62070. /**
  62071. * Sets wether tonemapping is enabled or not
  62072. */
  62073. set: function (value) {
  62074. this._imageProcessingConfiguration.toneMappingEnabled = value;
  62075. },
  62076. enumerable: true,
  62077. configurable: true
  62078. });
  62079. ;
  62080. ;
  62081. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  62082. /**
  62083. * Gets contrast used in the effect.
  62084. */
  62085. get: function () {
  62086. return this.imageProcessingConfiguration.contrast;
  62087. },
  62088. /**
  62089. * Sets contrast used in the effect.
  62090. */
  62091. set: function (value) {
  62092. this.imageProcessingConfiguration.contrast = value;
  62093. },
  62094. enumerable: true,
  62095. configurable: true
  62096. });
  62097. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  62098. /**
  62099. * Gets Vignette stretch size.
  62100. */
  62101. get: function () {
  62102. return this.imageProcessingConfiguration.vignetteStretch;
  62103. },
  62104. /**
  62105. * Sets Vignette stretch size.
  62106. */
  62107. set: function (value) {
  62108. this.imageProcessingConfiguration.vignetteStretch = value;
  62109. },
  62110. enumerable: true,
  62111. configurable: true
  62112. });
  62113. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  62114. /**
  62115. * Gets Vignette centre X Offset.
  62116. */
  62117. get: function () {
  62118. return this.imageProcessingConfiguration.vignetteCentreX;
  62119. },
  62120. /**
  62121. * Sets Vignette centre X Offset.
  62122. */
  62123. set: function (value) {
  62124. this.imageProcessingConfiguration.vignetteCentreX = value;
  62125. },
  62126. enumerable: true,
  62127. configurable: true
  62128. });
  62129. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  62130. /**
  62131. * Gets Vignette centre Y Offset.
  62132. */
  62133. get: function () {
  62134. return this.imageProcessingConfiguration.vignetteCentreY;
  62135. },
  62136. /**
  62137. * Sets Vignette centre Y Offset.
  62138. */
  62139. set: function (value) {
  62140. this.imageProcessingConfiguration.vignetteCentreY = value;
  62141. },
  62142. enumerable: true,
  62143. configurable: true
  62144. });
  62145. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  62146. /**
  62147. * Gets Vignette weight or intensity of the vignette effect.
  62148. */
  62149. get: function () {
  62150. return this.imageProcessingConfiguration.vignetteWeight;
  62151. },
  62152. /**
  62153. * Sets Vignette weight or intensity of the vignette effect.
  62154. */
  62155. set: function (value) {
  62156. this.imageProcessingConfiguration.vignetteWeight = value;
  62157. },
  62158. enumerable: true,
  62159. configurable: true
  62160. });
  62161. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  62162. /**
  62163. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  62164. * if vignetteEnabled is set to true.
  62165. */
  62166. get: function () {
  62167. return this.imageProcessingConfiguration.vignetteColor;
  62168. },
  62169. /**
  62170. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  62171. * if vignetteEnabled is set to true.
  62172. */
  62173. set: function (value) {
  62174. this.imageProcessingConfiguration.vignetteColor = value;
  62175. },
  62176. enumerable: true,
  62177. configurable: true
  62178. });
  62179. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  62180. /**
  62181. * Gets Camera field of view used by the Vignette effect.
  62182. */
  62183. get: function () {
  62184. return this.imageProcessingConfiguration.vignetteCameraFov;
  62185. },
  62186. /**
  62187. * Sets Camera field of view used by the Vignette effect.
  62188. */
  62189. set: function (value) {
  62190. this.imageProcessingConfiguration.vignetteCameraFov = value;
  62191. },
  62192. enumerable: true,
  62193. configurable: true
  62194. });
  62195. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  62196. /**
  62197. * Gets the vignette blend mode allowing different kind of effect.
  62198. */
  62199. get: function () {
  62200. return this.imageProcessingConfiguration.vignetteBlendMode;
  62201. },
  62202. /**
  62203. * Sets the vignette blend mode allowing different kind of effect.
  62204. */
  62205. set: function (value) {
  62206. this.imageProcessingConfiguration.vignetteBlendMode = value;
  62207. },
  62208. enumerable: true,
  62209. configurable: true
  62210. });
  62211. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  62212. /**
  62213. * Gets wether the vignette effect is enabled.
  62214. */
  62215. get: function () {
  62216. return this.imageProcessingConfiguration.vignetteEnabled;
  62217. },
  62218. /**
  62219. * Sets wether the vignette effect is enabled.
  62220. */
  62221. set: function (value) {
  62222. this.imageProcessingConfiguration.vignetteEnabled = value;
  62223. },
  62224. enumerable: true,
  62225. configurable: true
  62226. });
  62227. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  62228. /**
  62229. * Gets wether the input of the processing is in Gamma or Linear Space.
  62230. */
  62231. get: function () {
  62232. return this._fromLinearSpace;
  62233. },
  62234. /**
  62235. * Sets wether the input of the processing is in Gamma or Linear Space.
  62236. */
  62237. set: function (value) {
  62238. if (this._fromLinearSpace === value) {
  62239. return;
  62240. }
  62241. this._fromLinearSpace = value;
  62242. this._updateParameters();
  62243. },
  62244. enumerable: true,
  62245. configurable: true
  62246. });
  62247. ImageProcessingPostProcess.prototype.getClassName = function () {
  62248. return "ImageProcessingPostProcess";
  62249. };
  62250. ImageProcessingPostProcess.prototype._updateParameters = function () {
  62251. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  62252. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  62253. var defines = "";
  62254. for (var define in this._defines) {
  62255. if (this._defines[define]) {
  62256. defines += "#define " + define + ";\r\n";
  62257. }
  62258. }
  62259. var samplers = ["textureSampler"];
  62260. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  62261. var uniforms = ["scale"];
  62262. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  62263. this.updateEffect(defines, uniforms, samplers);
  62264. };
  62265. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  62266. _super.prototype.dispose.call(this, camera);
  62267. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  62268. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  62269. }
  62270. this.imageProcessingConfiguration.applyByPostProcess = false;
  62271. };
  62272. __decorate([
  62273. BABYLON.serialize()
  62274. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  62275. return ImageProcessingPostProcess;
  62276. }(BABYLON.PostProcess));
  62277. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  62278. })(BABYLON || (BABYLON = {}));
  62279. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  62280. var BABYLON;
  62281. (function (BABYLON) {
  62282. var BlurPostProcess = /** @class */ (function (_super) {
  62283. __extends(BlurPostProcess, _super);
  62284. function BlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable, textureType) {
  62285. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  62286. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  62287. var _this = _super.call(this, name, "kernelBlur", ["delta", "direction"], null, options, camera, samplingMode, engine, reusable, null, textureType, "kernelBlur", { varyingCount: 0, depCount: 0 }, true) || this;
  62288. _this.direction = direction;
  62289. _this._packedFloat = false;
  62290. _this.onApplyObservable.add(function (effect) {
  62291. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  62292. });
  62293. _this.kernel = kernel;
  62294. return _this;
  62295. }
  62296. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  62297. /**
  62298. * Gets the length in pixels of the blur sample region
  62299. */
  62300. get: function () {
  62301. return this._idealKernel;
  62302. },
  62303. /**
  62304. * Sets the length in pixels of the blur sample region
  62305. */
  62306. set: function (v) {
  62307. if (this._idealKernel === v) {
  62308. return;
  62309. }
  62310. v = Math.max(v, 1);
  62311. this._idealKernel = v;
  62312. this._kernel = this._nearestBestKernel(v);
  62313. this._updateParameters();
  62314. },
  62315. enumerable: true,
  62316. configurable: true
  62317. });
  62318. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  62319. /**
  62320. * Gets wether or not the blur is unpacking/repacking floats
  62321. */
  62322. get: function () {
  62323. return this._packedFloat;
  62324. },
  62325. /**
  62326. * Sets wether or not the blur needs to unpack/repack floats
  62327. */
  62328. set: function (v) {
  62329. if (this._packedFloat === v) {
  62330. return;
  62331. }
  62332. this._packedFloat = v;
  62333. this._updateParameters();
  62334. },
  62335. enumerable: true,
  62336. configurable: true
  62337. });
  62338. BlurPostProcess.prototype._updateParameters = function () {
  62339. // Generate sampling offsets and weights
  62340. var N = this._kernel;
  62341. var centerIndex = (N - 1) / 2;
  62342. // Generate Gaussian sampling weights over kernel
  62343. var offsets = [];
  62344. var weights = [];
  62345. var totalWeight = 0;
  62346. for (var i = 0; i < N; i++) {
  62347. var u = i / (N - 1);
  62348. var w = this._gaussianWeight(u * 2.0 - 1);
  62349. offsets[i] = (i - centerIndex);
  62350. weights[i] = w;
  62351. totalWeight += w;
  62352. }
  62353. // Normalize weights
  62354. for (var i = 0; i < weights.length; i++) {
  62355. weights[i] /= totalWeight;
  62356. }
  62357. // Optimize: combine samples to take advantage of hardware linear sampling
  62358. // Walk from left to center, combining pairs (symmetrically)
  62359. var linearSamplingWeights = [];
  62360. var linearSamplingOffsets = [];
  62361. var linearSamplingMap = [];
  62362. for (var i = 0; i <= centerIndex; i += 2) {
  62363. var j = Math.min(i + 1, Math.floor(centerIndex));
  62364. var singleCenterSample = i === j;
  62365. if (singleCenterSample) {
  62366. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  62367. }
  62368. else {
  62369. var sharedCell = j === centerIndex;
  62370. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  62371. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  62372. if (offsetLinear === 0) {
  62373. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  62374. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  62375. }
  62376. else {
  62377. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  62378. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  62379. }
  62380. }
  62381. }
  62382. for (var i = 0; i < linearSamplingMap.length; i++) {
  62383. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  62384. linearSamplingWeights[i] = linearSamplingMap[i].w;
  62385. }
  62386. // Replace with optimized
  62387. offsets = linearSamplingOffsets;
  62388. weights = linearSamplingWeights;
  62389. // Generate shaders
  62390. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  62391. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  62392. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  62393. var defines = "";
  62394. for (var i = 0; i < varyingCount; i++) {
  62395. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  62396. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  62397. }
  62398. var depCount = 0;
  62399. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  62400. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  62401. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  62402. depCount++;
  62403. }
  62404. if (this.packedFloat) {
  62405. defines += "#define PACKEDFLOAT 1";
  62406. }
  62407. this.updateEffect(defines, null, null, {
  62408. varyingCount: varyingCount,
  62409. depCount: depCount
  62410. });
  62411. };
  62412. /**
  62413. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  62414. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  62415. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  62416. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  62417. * The gaps between physical kernels are compensated for in the weighting of the samples
  62418. * @param idealKernel Ideal blur kernel.
  62419. * @return Nearest best kernel.
  62420. */
  62421. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  62422. var v = Math.round(idealKernel);
  62423. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  62424. var k = _a[_i];
  62425. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  62426. return Math.max(k, 3);
  62427. }
  62428. }
  62429. return Math.max(v, 3);
  62430. };
  62431. /**
  62432. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  62433. * @param x The point on the Gaussian distribution to sample.
  62434. * @return the value of the Gaussian function at x.
  62435. */
  62436. BlurPostProcess.prototype._gaussianWeight = function (x) {
  62437. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  62438. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  62439. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  62440. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  62441. // truncated at around 1.3% of peak strength.
  62442. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  62443. var sigma = (1 / 3);
  62444. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  62445. var exponent = -((x * x) / (2.0 * sigma * sigma));
  62446. var weight = (1.0 / denominator) * Math.exp(exponent);
  62447. return weight;
  62448. };
  62449. /**
  62450. * Generates a string that can be used as a floating point number in GLSL.
  62451. * @param x Value to print.
  62452. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  62453. * @return GLSL float string.
  62454. */
  62455. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  62456. if (decimalFigures === void 0) { decimalFigures = 8; }
  62457. return x.toFixed(decimalFigures).replace(/0+$/, '');
  62458. };
  62459. return BlurPostProcess;
  62460. }(BABYLON.PostProcess));
  62461. BABYLON.BlurPostProcess = BlurPostProcess;
  62462. })(BABYLON || (BABYLON = {}));
  62463. //# sourceMappingURL=babylon.blurPostProcess.js.map
  62464. var BABYLON;
  62465. (function (BABYLON) {
  62466. var Bone = /** @class */ (function (_super) {
  62467. __extends(Bone, _super);
  62468. function Bone(name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  62469. if (parentBone === void 0) { parentBone = null; }
  62470. if (localMatrix === void 0) { localMatrix = null; }
  62471. if (restPose === void 0) { restPose = null; }
  62472. if (baseMatrix === void 0) { baseMatrix = null; }
  62473. if (index === void 0) { index = null; }
  62474. var _this = _super.call(this, name, skeleton.getScene()) || this;
  62475. _this.name = name;
  62476. _this.children = new Array();
  62477. _this.animations = new Array();
  62478. // Set this value to map this bone to a different index in the transform matrices.
  62479. // Set this value to -1 to exclude the bone from the transform matrices.
  62480. _this._index = null;
  62481. _this._worldTransform = new BABYLON.Matrix();
  62482. _this._absoluteTransform = new BABYLON.Matrix();
  62483. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  62484. _this._scaleMatrix = BABYLON.Matrix.Identity();
  62485. _this._scaleVector = BABYLON.Vector3.One();
  62486. _this._negateScaleChildren = BABYLON.Vector3.One();
  62487. _this._scalingDeterminant = 1;
  62488. _this._skeleton = skeleton;
  62489. _this._localMatrix = localMatrix ? localMatrix : BABYLON.Matrix.Identity();
  62490. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  62491. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  62492. _this._index = index;
  62493. skeleton.bones.push(_this);
  62494. _this.setParent(parentBone, false);
  62495. _this._updateDifferenceMatrix();
  62496. return _this;
  62497. }
  62498. Object.defineProperty(Bone.prototype, "_matrix", {
  62499. get: function () {
  62500. return this._localMatrix;
  62501. },
  62502. set: function (val) {
  62503. if (this._localMatrix) {
  62504. this._localMatrix.copyFrom(val);
  62505. }
  62506. else {
  62507. this._localMatrix = val;
  62508. }
  62509. },
  62510. enumerable: true,
  62511. configurable: true
  62512. });
  62513. // Members
  62514. Bone.prototype.getSkeleton = function () {
  62515. return this._skeleton;
  62516. };
  62517. Bone.prototype.getParent = function () {
  62518. return this._parent;
  62519. };
  62520. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  62521. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  62522. if (this._parent === parent) {
  62523. return;
  62524. }
  62525. if (this._parent) {
  62526. var index = this._parent.children.indexOf(this);
  62527. if (index !== -1) {
  62528. this._parent.children.splice(index, 1);
  62529. }
  62530. }
  62531. this._parent = parent;
  62532. if (this._parent) {
  62533. this._parent.children.push(this);
  62534. }
  62535. if (updateDifferenceMatrix) {
  62536. this._updateDifferenceMatrix();
  62537. }
  62538. };
  62539. Bone.prototype.getLocalMatrix = function () {
  62540. return this._localMatrix;
  62541. };
  62542. Bone.prototype.getBaseMatrix = function () {
  62543. return this._baseMatrix;
  62544. };
  62545. Bone.prototype.getRestPose = function () {
  62546. return this._restPose;
  62547. };
  62548. Bone.prototype.returnToRest = function () {
  62549. this.updateMatrix(this._restPose.clone());
  62550. };
  62551. Bone.prototype.getWorldMatrix = function () {
  62552. return this._worldTransform;
  62553. };
  62554. Bone.prototype.getInvertedAbsoluteTransform = function () {
  62555. return this._invertedAbsoluteTransform;
  62556. };
  62557. Bone.prototype.getAbsoluteTransform = function () {
  62558. return this._absoluteTransform;
  62559. };
  62560. Object.defineProperty(Bone.prototype, "position", {
  62561. // Properties (matches AbstractMesh properties)
  62562. get: function () {
  62563. return this.getPosition();
  62564. },
  62565. set: function (newPosition) {
  62566. this.setPosition(newPosition);
  62567. },
  62568. enumerable: true,
  62569. configurable: true
  62570. });
  62571. Object.defineProperty(Bone.prototype, "rotation", {
  62572. get: function () {
  62573. return this.getRotation();
  62574. },
  62575. set: function (newRotation) {
  62576. this.setRotation(newRotation);
  62577. },
  62578. enumerable: true,
  62579. configurable: true
  62580. });
  62581. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  62582. get: function () {
  62583. return this.getRotationQuaternion();
  62584. },
  62585. set: function (newRotation) {
  62586. this.setRotationQuaternion(newRotation);
  62587. },
  62588. enumerable: true,
  62589. configurable: true
  62590. });
  62591. Object.defineProperty(Bone.prototype, "scaling", {
  62592. get: function () {
  62593. return this.getScale();
  62594. },
  62595. set: function (newScaling) {
  62596. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  62597. },
  62598. enumerable: true,
  62599. configurable: true
  62600. });
  62601. // Methods
  62602. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  62603. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  62604. this._baseMatrix = matrix.clone();
  62605. this._localMatrix = matrix.clone();
  62606. this._skeleton._markAsDirty();
  62607. if (updateDifferenceMatrix) {
  62608. this._updateDifferenceMatrix();
  62609. }
  62610. };
  62611. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  62612. if (!rootMatrix) {
  62613. rootMatrix = this._baseMatrix;
  62614. }
  62615. if (this._parent) {
  62616. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  62617. }
  62618. else {
  62619. this._absoluteTransform.copyFrom(rootMatrix);
  62620. }
  62621. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  62622. for (var index = 0; index < this.children.length; index++) {
  62623. this.children[index]._updateDifferenceMatrix();
  62624. }
  62625. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  62626. };
  62627. Bone.prototype.markAsDirty = function () {
  62628. this._currentRenderId++;
  62629. this._skeleton._markAsDirty();
  62630. };
  62631. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  62632. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  62633. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  62634. // all animation may be coming from a library skeleton, so may need to create animation
  62635. if (this.animations.length === 0) {
  62636. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  62637. this.animations[0].setKeys([]);
  62638. }
  62639. // get animation info / verify there is such a range from the source bone
  62640. var sourceRange = source.animations[0].getRange(rangeName);
  62641. if (!sourceRange) {
  62642. return false;
  62643. }
  62644. var from = sourceRange.from;
  62645. var to = sourceRange.to;
  62646. var sourceKeys = source.animations[0].getKeys();
  62647. // rescaling prep
  62648. var sourceBoneLength = source.length;
  62649. var sourceParent = source.getParent();
  62650. var parent = this.getParent();
  62651. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  62652. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  62653. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  62654. var destKeys = this.animations[0].getKeys();
  62655. // loop vars declaration
  62656. var orig;
  62657. var origTranslation;
  62658. var mat;
  62659. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  62660. orig = sourceKeys[key];
  62661. if (orig.frame >= from && orig.frame <= to) {
  62662. if (rescaleAsRequired) {
  62663. mat = orig.value.clone();
  62664. // scale based on parent ratio, when bone has parent
  62665. if (parentScalingReqd) {
  62666. origTranslation = mat.getTranslation();
  62667. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  62668. // scale based on skeleton dimension ratio when root bone, and value is passed
  62669. }
  62670. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  62671. origTranslation = mat.getTranslation();
  62672. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  62673. // use original when root bone, and no data for skelDimensionsRatio
  62674. }
  62675. else {
  62676. mat = orig.value;
  62677. }
  62678. }
  62679. else {
  62680. mat = orig.value;
  62681. }
  62682. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  62683. }
  62684. }
  62685. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  62686. return true;
  62687. };
  62688. /**
  62689. * Translate the bone in local or world space.
  62690. * @param vec The amount to translate the bone.
  62691. * @param space The space that the translation is in.
  62692. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  62693. */
  62694. Bone.prototype.translate = function (vec, space, mesh) {
  62695. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  62696. var lm = this.getLocalMatrix();
  62697. if (space == BABYLON.Space.LOCAL) {
  62698. lm.m[12] += vec.x;
  62699. lm.m[13] += vec.y;
  62700. lm.m[14] += vec.z;
  62701. }
  62702. else {
  62703. var wm = null;
  62704. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  62705. if (mesh) {
  62706. wm = mesh.getWorldMatrix();
  62707. }
  62708. this._skeleton.computeAbsoluteTransforms();
  62709. var tmat = Bone._tmpMats[0];
  62710. var tvec = Bone._tmpVecs[0];
  62711. if (this._parent) {
  62712. if (mesh && wm) {
  62713. tmat.copyFrom(this._parent.getAbsoluteTransform());
  62714. tmat.multiplyToRef(wm, tmat);
  62715. }
  62716. else {
  62717. tmat.copyFrom(this._parent.getAbsoluteTransform());
  62718. }
  62719. }
  62720. tmat.m[12] = 0;
  62721. tmat.m[13] = 0;
  62722. tmat.m[14] = 0;
  62723. tmat.invert();
  62724. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  62725. lm.m[12] += tvec.x;
  62726. lm.m[13] += tvec.y;
  62727. lm.m[14] += tvec.z;
  62728. }
  62729. this.markAsDirty();
  62730. };
  62731. /**
  62732. * Set the postion of the bone in local or world space.
  62733. * @param position The position to set the bone.
  62734. * @param space The space that the position is in.
  62735. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  62736. */
  62737. Bone.prototype.setPosition = function (position, space, mesh) {
  62738. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  62739. var lm = this.getLocalMatrix();
  62740. if (space == BABYLON.Space.LOCAL) {
  62741. lm.m[12] = position.x;
  62742. lm.m[13] = position.y;
  62743. lm.m[14] = position.z;
  62744. }
  62745. else {
  62746. var wm = null;
  62747. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  62748. if (mesh) {
  62749. wm = mesh.getWorldMatrix();
  62750. }
  62751. this._skeleton.computeAbsoluteTransforms();
  62752. var tmat = Bone._tmpMats[0];
  62753. var vec = Bone._tmpVecs[0];
  62754. if (this._parent) {
  62755. if (mesh && wm) {
  62756. tmat.copyFrom(this._parent.getAbsoluteTransform());
  62757. tmat.multiplyToRef(wm, tmat);
  62758. }
  62759. else {
  62760. tmat.copyFrom(this._parent.getAbsoluteTransform());
  62761. }
  62762. }
  62763. tmat.invert();
  62764. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  62765. lm.m[12] = vec.x;
  62766. lm.m[13] = vec.y;
  62767. lm.m[14] = vec.z;
  62768. }
  62769. this.markAsDirty();
  62770. };
  62771. /**
  62772. * Set the absolute postion of the bone (world space).
  62773. * @param position The position to set the bone.
  62774. * @param mesh The mesh that this bone is attached to.
  62775. */
  62776. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  62777. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  62778. };
  62779. /**
  62780. * Set the scale of the bone on the x, y and z axes.
  62781. * @param x The scale of the bone on the x axis.
  62782. * @param x The scale of the bone on the y axis.
  62783. * @param z The scale of the bone on the z axis.
  62784. * @param scaleChildren Set this to true if children of the bone should be scaled.
  62785. */
  62786. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  62787. if (scaleChildren === void 0) { scaleChildren = false; }
  62788. if (this.animations[0] && !this.animations[0].hasRunningRuntimeAnimations) {
  62789. if (!scaleChildren) {
  62790. this._negateScaleChildren.x = 1 / x;
  62791. this._negateScaleChildren.y = 1 / y;
  62792. this._negateScaleChildren.z = 1 / z;
  62793. }
  62794. this._syncScaleVector();
  62795. }
  62796. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  62797. };
  62798. /**
  62799. * Scale the bone on the x, y and z axes.
  62800. * @param x The amount to scale the bone on the x axis.
  62801. * @param x The amount to scale the bone on the y axis.
  62802. * @param z The amount to scale the bone on the z axis.
  62803. * @param scaleChildren Set this to true if children of the bone should be scaled.
  62804. */
  62805. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  62806. if (scaleChildren === void 0) { scaleChildren = false; }
  62807. var locMat = this.getLocalMatrix();
  62808. var origLocMat = Bone._tmpMats[0];
  62809. origLocMat.copyFrom(locMat);
  62810. var origLocMatInv = Bone._tmpMats[1];
  62811. origLocMatInv.copyFrom(origLocMat);
  62812. origLocMatInv.invert();
  62813. var scaleMat = Bone._tmpMats[2];
  62814. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  62815. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  62816. this._scaleVector.x *= x;
  62817. this._scaleVector.y *= y;
  62818. this._scaleVector.z *= z;
  62819. locMat.multiplyToRef(origLocMatInv, locMat);
  62820. locMat.multiplyToRef(scaleMat, locMat);
  62821. locMat.multiplyToRef(origLocMat, locMat);
  62822. var parent = this.getParent();
  62823. if (parent) {
  62824. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  62825. }
  62826. else {
  62827. this.getAbsoluteTransform().copyFrom(locMat);
  62828. }
  62829. var len = this.children.length;
  62830. scaleMat.invert();
  62831. for (var i = 0; i < len; i++) {
  62832. var child = this.children[i];
  62833. var cm = child.getLocalMatrix();
  62834. cm.multiplyToRef(scaleMat, cm);
  62835. var lm = child.getLocalMatrix();
  62836. lm.m[12] *= x;
  62837. lm.m[13] *= y;
  62838. lm.m[14] *= z;
  62839. }
  62840. this.computeAbsoluteTransforms();
  62841. if (scaleChildren) {
  62842. for (var i = 0; i < len; i++) {
  62843. this.children[i].scale(x, y, z, scaleChildren);
  62844. }
  62845. }
  62846. this.markAsDirty();
  62847. };
  62848. /**
  62849. * Set the yaw, pitch, and roll of the bone in local or world space.
  62850. * @param yaw The rotation of the bone on the y axis.
  62851. * @param pitch The rotation of the bone on the x axis.
  62852. * @param roll The rotation of the bone on the z axis.
  62853. * @param space The space that the axes of rotation are in.
  62854. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  62855. */
  62856. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  62857. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  62858. var rotMat = Bone._tmpMats[0];
  62859. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  62860. var rotMatInv = Bone._tmpMats[1];
  62861. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  62862. rotMatInv.multiplyToRef(rotMat, rotMat);
  62863. this._rotateWithMatrix(rotMat, space, mesh);
  62864. };
  62865. /**
  62866. * Rotate the bone on an axis in local or world space.
  62867. * @param axis The axis to rotate the bone on.
  62868. * @param amount The amount to rotate the bone.
  62869. * @param space The space that the axis is in.
  62870. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  62871. */
  62872. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  62873. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  62874. var rmat = Bone._tmpMats[0];
  62875. rmat.m[12] = 0;
  62876. rmat.m[13] = 0;
  62877. rmat.m[14] = 0;
  62878. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  62879. this._rotateWithMatrix(rmat, space, mesh);
  62880. };
  62881. /**
  62882. * Set the rotation of the bone to a particular axis angle in local or world space.
  62883. * @param axis The axis to rotate the bone on.
  62884. * @param angle The angle that the bone should be rotated to.
  62885. * @param space The space that the axis is in.
  62886. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  62887. */
  62888. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  62889. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  62890. var rotMat = Bone._tmpMats[0];
  62891. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  62892. var rotMatInv = Bone._tmpMats[1];
  62893. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  62894. rotMatInv.multiplyToRef(rotMat, rotMat);
  62895. this._rotateWithMatrix(rotMat, space, mesh);
  62896. };
  62897. /**
  62898. * Set the euler rotation of the bone in local of world space.
  62899. * @param rotation The euler rotation that the bone should be set to.
  62900. * @param space The space that the rotation is in.
  62901. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  62902. */
  62903. Bone.prototype.setRotation = function (rotation, space, mesh) {
  62904. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  62905. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  62906. };
  62907. /**
  62908. * Set the quaternion rotation of the bone in local of world space.
  62909. * @param quat The quaternion rotation that the bone should be set to.
  62910. * @param space The space that the rotation is in.
  62911. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  62912. */
  62913. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  62914. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  62915. var rotMatInv = Bone._tmpMats[0];
  62916. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  62917. var rotMat = Bone._tmpMats[1];
  62918. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  62919. rotMatInv.multiplyToRef(rotMat, rotMat);
  62920. this._rotateWithMatrix(rotMat, space, mesh);
  62921. };
  62922. /**
  62923. * Set the rotation matrix of the bone in local of world space.
  62924. * @param rotMat The rotation matrix that the bone should be set to.
  62925. * @param space The space that the rotation is in.
  62926. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  62927. */
  62928. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  62929. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  62930. var rotMatInv = Bone._tmpMats[0];
  62931. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  62932. var rotMat2 = Bone._tmpMats[1];
  62933. rotMat2.copyFrom(rotMat);
  62934. rotMatInv.multiplyToRef(rotMat, rotMat2);
  62935. this._rotateWithMatrix(rotMat2, space, mesh);
  62936. };
  62937. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  62938. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  62939. var lmat = this.getLocalMatrix();
  62940. var lx = lmat.m[12];
  62941. var ly = lmat.m[13];
  62942. var lz = lmat.m[14];
  62943. var parent = this.getParent();
  62944. var parentScale = Bone._tmpMats[3];
  62945. var parentScaleInv = Bone._tmpMats[4];
  62946. if (parent) {
  62947. if (space == BABYLON.Space.WORLD) {
  62948. if (mesh) {
  62949. parentScale.copyFrom(mesh.getWorldMatrix());
  62950. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  62951. }
  62952. else {
  62953. parentScale.copyFrom(parent.getAbsoluteTransform());
  62954. }
  62955. }
  62956. else {
  62957. parentScale = parent._scaleMatrix;
  62958. }
  62959. parentScaleInv.copyFrom(parentScale);
  62960. parentScaleInv.invert();
  62961. lmat.multiplyToRef(parentScale, lmat);
  62962. lmat.multiplyToRef(rmat, lmat);
  62963. lmat.multiplyToRef(parentScaleInv, lmat);
  62964. }
  62965. else {
  62966. if (space == BABYLON.Space.WORLD && mesh) {
  62967. parentScale.copyFrom(mesh.getWorldMatrix());
  62968. parentScaleInv.copyFrom(parentScale);
  62969. parentScaleInv.invert();
  62970. lmat.multiplyToRef(parentScale, lmat);
  62971. lmat.multiplyToRef(rmat, lmat);
  62972. lmat.multiplyToRef(parentScaleInv, lmat);
  62973. }
  62974. else {
  62975. lmat.multiplyToRef(rmat, lmat);
  62976. }
  62977. }
  62978. lmat.m[12] = lx;
  62979. lmat.m[13] = ly;
  62980. lmat.m[14] = lz;
  62981. this.computeAbsoluteTransforms();
  62982. this.markAsDirty();
  62983. };
  62984. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  62985. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  62986. if (space == BABYLON.Space.WORLD) {
  62987. var scaleMatrix = Bone._tmpMats[2];
  62988. scaleMatrix.copyFrom(this._scaleMatrix);
  62989. rotMatInv.copyFrom(this.getAbsoluteTransform());
  62990. if (mesh) {
  62991. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  62992. var meshScale = Bone._tmpMats[3];
  62993. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  62994. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  62995. }
  62996. rotMatInv.invert();
  62997. scaleMatrix.m[0] *= this._scalingDeterminant;
  62998. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  62999. }
  63000. else {
  63001. rotMatInv.copyFrom(this.getLocalMatrix());
  63002. rotMatInv.invert();
  63003. var scaleMatrix = Bone._tmpMats[2];
  63004. scaleMatrix.copyFrom(this._scaleMatrix);
  63005. if (this._parent) {
  63006. var pscaleMatrix = Bone._tmpMats[3];
  63007. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  63008. pscaleMatrix.invert();
  63009. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  63010. }
  63011. else {
  63012. scaleMatrix.m[0] *= this._scalingDeterminant;
  63013. }
  63014. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  63015. }
  63016. };
  63017. /**
  63018. * Get the scale of the bone
  63019. * @returns the scale of the bone
  63020. */
  63021. Bone.prototype.getScale = function () {
  63022. return this._scaleVector.clone();
  63023. };
  63024. /**
  63025. * Copy the scale of the bone to a vector3.
  63026. * @param result The vector3 to copy the scale to
  63027. */
  63028. Bone.prototype.getScaleToRef = function (result) {
  63029. result.copyFrom(this._scaleVector);
  63030. };
  63031. /**
  63032. * Get the position of the bone in local or world space.
  63033. * @param space The space that the returned position is in.
  63034. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63035. * @returns The position of the bone
  63036. */
  63037. Bone.prototype.getPosition = function (space, mesh) {
  63038. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63039. if (mesh === void 0) { mesh = null; }
  63040. var pos = BABYLON.Vector3.Zero();
  63041. this.getPositionToRef(space, mesh, pos);
  63042. return pos;
  63043. };
  63044. /**
  63045. * Copy the position of the bone to a vector3 in local or world space.
  63046. * @param space The space that the returned position is in.
  63047. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63048. * @param result The vector3 to copy the position to.
  63049. */
  63050. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  63051. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63052. if (space == BABYLON.Space.LOCAL) {
  63053. var lm = this.getLocalMatrix();
  63054. result.x = lm.m[12];
  63055. result.y = lm.m[13];
  63056. result.z = lm.m[14];
  63057. }
  63058. else {
  63059. var wm = null;
  63060. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  63061. if (mesh) {
  63062. wm = mesh.getWorldMatrix();
  63063. }
  63064. this._skeleton.computeAbsoluteTransforms();
  63065. var tmat = Bone._tmpMats[0];
  63066. if (mesh && wm) {
  63067. tmat.copyFrom(this.getAbsoluteTransform());
  63068. tmat.multiplyToRef(wm, tmat);
  63069. }
  63070. else {
  63071. tmat = this.getAbsoluteTransform();
  63072. }
  63073. result.x = tmat.m[12];
  63074. result.y = tmat.m[13];
  63075. result.z = tmat.m[14];
  63076. }
  63077. };
  63078. /**
  63079. * Get the absolute position of the bone (world space).
  63080. * @param mesh The mesh that this bone is attached to.
  63081. * @returns The absolute position of the bone
  63082. */
  63083. Bone.prototype.getAbsolutePosition = function (mesh) {
  63084. if (mesh === void 0) { mesh = null; }
  63085. var pos = BABYLON.Vector3.Zero();
  63086. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  63087. return pos;
  63088. };
  63089. /**
  63090. * Copy the absolute position of the bone (world space) to the result param.
  63091. * @param mesh The mesh that this bone is attached to.
  63092. * @param result The vector3 to copy the absolute position to.
  63093. */
  63094. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  63095. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  63096. };
  63097. /**
  63098. * Compute the absolute transforms of this bone and its children.
  63099. */
  63100. Bone.prototype.computeAbsoluteTransforms = function () {
  63101. if (this._parent) {
  63102. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  63103. }
  63104. else {
  63105. this._absoluteTransform.copyFrom(this._localMatrix);
  63106. var poseMatrix = this._skeleton.getPoseMatrix();
  63107. if (poseMatrix) {
  63108. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  63109. }
  63110. }
  63111. var children = this.children;
  63112. var len = children.length;
  63113. for (var i = 0; i < len; i++) {
  63114. children[i].computeAbsoluteTransforms();
  63115. }
  63116. };
  63117. Bone.prototype._syncScaleVector = function () {
  63118. var lm = this.getLocalMatrix();
  63119. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  63120. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  63121. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  63122. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  63123. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  63124. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  63125. this._scaleVector.x = xs * Math.sqrt(xsq);
  63126. this._scaleVector.y = ys * Math.sqrt(ysq);
  63127. this._scaleVector.z = zs * Math.sqrt(zsq);
  63128. if (this._parent) {
  63129. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  63130. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  63131. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  63132. }
  63133. 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);
  63134. };
  63135. /**
  63136. * Get the world direction from an axis that is in the local space of the bone.
  63137. * @param localAxis The local direction that is used to compute the world direction.
  63138. * @param mesh The mesh that this bone is attached to.
  63139. * @returns The world direction
  63140. */
  63141. Bone.prototype.getDirection = function (localAxis, mesh) {
  63142. if (mesh === void 0) { mesh = null; }
  63143. var result = BABYLON.Vector3.Zero();
  63144. this.getDirectionToRef(localAxis, mesh, result);
  63145. return result;
  63146. };
  63147. /**
  63148. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  63149. * @param localAxis The local direction that is used to compute the world direction.
  63150. * @param mesh The mesh that this bone is attached to.
  63151. * @param result The vector3 that the world direction will be copied to.
  63152. */
  63153. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  63154. if (mesh === void 0) { mesh = null; }
  63155. var wm = null;
  63156. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  63157. if (mesh) {
  63158. wm = mesh.getWorldMatrix();
  63159. }
  63160. this._skeleton.computeAbsoluteTransforms();
  63161. var mat = Bone._tmpMats[0];
  63162. mat.copyFrom(this.getAbsoluteTransform());
  63163. if (mesh && wm) {
  63164. mat.multiplyToRef(wm, mat);
  63165. }
  63166. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  63167. result.normalize();
  63168. };
  63169. /**
  63170. * Get the euler rotation of the bone in local or world space.
  63171. * @param space The space that the rotation should be in.
  63172. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63173. * @returns The euler rotation
  63174. */
  63175. Bone.prototype.getRotation = function (space, mesh) {
  63176. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63177. if (mesh === void 0) { mesh = null; }
  63178. var result = BABYLON.Vector3.Zero();
  63179. this.getRotationToRef(space, mesh, result);
  63180. return result;
  63181. };
  63182. /**
  63183. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  63184. * @param space The space that the rotation should be in.
  63185. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63186. * @param result The vector3 that the rotation should be copied to.
  63187. */
  63188. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  63189. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63190. if (mesh === void 0) { mesh = null; }
  63191. var quat = Bone._tmpQuat;
  63192. this.getRotationQuaternionToRef(space, mesh, quat);
  63193. quat.toEulerAnglesToRef(result);
  63194. };
  63195. /**
  63196. * Get the quaternion rotation of the bone in either local or world space.
  63197. * @param space The space that the rotation should be in.
  63198. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63199. * @returns The quaternion rotation
  63200. */
  63201. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  63202. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63203. if (mesh === void 0) { mesh = null; }
  63204. var result = BABYLON.Quaternion.Identity();
  63205. this.getRotationQuaternionToRef(space, mesh, result);
  63206. return result;
  63207. };
  63208. /**
  63209. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  63210. * @param space The space that the rotation should be in.
  63211. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63212. * @param result The quaternion that the rotation should be copied to.
  63213. */
  63214. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  63215. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63216. if (mesh === void 0) { mesh = null; }
  63217. if (space == BABYLON.Space.LOCAL) {
  63218. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  63219. }
  63220. else {
  63221. var mat = Bone._tmpMats[0];
  63222. var amat = this.getAbsoluteTransform();
  63223. if (mesh) {
  63224. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  63225. }
  63226. else {
  63227. mat.copyFrom(amat);
  63228. }
  63229. mat.m[0] *= this._scalingDeterminant;
  63230. mat.m[1] *= this._scalingDeterminant;
  63231. mat.m[2] *= this._scalingDeterminant;
  63232. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  63233. }
  63234. };
  63235. /**
  63236. * Get the rotation matrix of the bone in local or world space.
  63237. * @param space The space that the rotation should be in.
  63238. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63239. * @returns The rotation matrix
  63240. */
  63241. Bone.prototype.getRotationMatrix = function (space, mesh) {
  63242. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63243. var result = BABYLON.Matrix.Identity();
  63244. this.getRotationMatrixToRef(space, mesh, result);
  63245. return result;
  63246. };
  63247. /**
  63248. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  63249. * @param space The space that the rotation should be in.
  63250. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  63251. * @param result The quaternion that the rotation should be copied to.
  63252. */
  63253. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  63254. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  63255. if (space == BABYLON.Space.LOCAL) {
  63256. this.getLocalMatrix().getRotationMatrixToRef(result);
  63257. }
  63258. else {
  63259. var mat = Bone._tmpMats[0];
  63260. var amat = this.getAbsoluteTransform();
  63261. if (mesh) {
  63262. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  63263. }
  63264. else {
  63265. mat.copyFrom(amat);
  63266. }
  63267. mat.m[0] *= this._scalingDeterminant;
  63268. mat.m[1] *= this._scalingDeterminant;
  63269. mat.m[2] *= this._scalingDeterminant;
  63270. mat.getRotationMatrixToRef(result);
  63271. }
  63272. };
  63273. /**
  63274. * Get the world position of a point that is in the local space of the bone.
  63275. * @param position The local position
  63276. * @param mesh The mesh that this bone is attached to.
  63277. * @returns The world position
  63278. */
  63279. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  63280. if (mesh === void 0) { mesh = null; }
  63281. var result = BABYLON.Vector3.Zero();
  63282. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  63283. return result;
  63284. };
  63285. /**
  63286. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  63287. * @param position The local position
  63288. * @param mesh The mesh that this bone is attached to.
  63289. * @param result The vector3 that the world position should be copied to.
  63290. */
  63291. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  63292. if (mesh === void 0) { mesh = null; }
  63293. var wm = null;
  63294. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  63295. if (mesh) {
  63296. wm = mesh.getWorldMatrix();
  63297. }
  63298. this._skeleton.computeAbsoluteTransforms();
  63299. var tmat = Bone._tmpMats[0];
  63300. if (mesh && wm) {
  63301. tmat.copyFrom(this.getAbsoluteTransform());
  63302. tmat.multiplyToRef(wm, tmat);
  63303. }
  63304. else {
  63305. tmat = this.getAbsoluteTransform();
  63306. }
  63307. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  63308. };
  63309. /**
  63310. * Get the local position of a point that is in world space.
  63311. * @param position The world position
  63312. * @param mesh The mesh that this bone is attached to.
  63313. * @returns The local position
  63314. */
  63315. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  63316. if (mesh === void 0) { mesh = null; }
  63317. var result = BABYLON.Vector3.Zero();
  63318. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  63319. return result;
  63320. };
  63321. /**
  63322. * Get the local position of a point that is in world space and copy it to the result param.
  63323. * @param position The world position
  63324. * @param mesh The mesh that this bone is attached to.
  63325. * @param result The vector3 that the local position should be copied to.
  63326. */
  63327. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  63328. if (mesh === void 0) { mesh = null; }
  63329. var wm = null;
  63330. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  63331. if (mesh) {
  63332. wm = mesh.getWorldMatrix();
  63333. }
  63334. this._skeleton.computeAbsoluteTransforms();
  63335. var tmat = Bone._tmpMats[0];
  63336. tmat.copyFrom(this.getAbsoluteTransform());
  63337. if (mesh && wm) {
  63338. tmat.multiplyToRef(wm, tmat);
  63339. }
  63340. tmat.invert();
  63341. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  63342. };
  63343. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  63344. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  63345. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  63346. return Bone;
  63347. }(BABYLON.Node));
  63348. BABYLON.Bone = Bone;
  63349. })(BABYLON || (BABYLON = {}));
  63350. //# sourceMappingURL=babylon.bone.js.map
  63351. var BABYLON;
  63352. (function (BABYLON) {
  63353. var BoneIKController = /** @class */ (function () {
  63354. function BoneIKController(mesh, bone, options) {
  63355. this.targetPosition = BABYLON.Vector3.Zero();
  63356. this.poleTargetPosition = BABYLON.Vector3.Zero();
  63357. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  63358. this.poleAngle = 0;
  63359. this.slerpAmount = 1;
  63360. this._bone1Quat = BABYLON.Quaternion.Identity();
  63361. this._bone1Mat = BABYLON.Matrix.Identity();
  63362. this._bone2Ang = Math.PI;
  63363. this._maxAngle = Math.PI;
  63364. this._rightHandedSystem = false;
  63365. this._bendAxis = BABYLON.Vector3.Right();
  63366. this._slerping = false;
  63367. this._adjustRoll = 0;
  63368. this._bone2 = bone;
  63369. this._bone1 = bone.getParent();
  63370. if (!this._bone1) {
  63371. return;
  63372. }
  63373. this.mesh = mesh;
  63374. var bonePos = bone.getPosition();
  63375. if (bone.getAbsoluteTransform().determinant() > 0) {
  63376. this._rightHandedSystem = true;
  63377. this._bendAxis.x = 0;
  63378. this._bendAxis.y = 0;
  63379. this._bendAxis.z = -1;
  63380. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  63381. this._adjustRoll = Math.PI * .5;
  63382. this._bendAxis.z = 1;
  63383. }
  63384. }
  63385. if (this._bone1.length) {
  63386. var boneScale1 = this._bone1.getScale();
  63387. var boneScale2 = this._bone2.getScale();
  63388. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  63389. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  63390. }
  63391. else if (this._bone1.children[0]) {
  63392. mesh.computeWorldMatrix(true);
  63393. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  63394. var pos2 = this._bone2.getAbsolutePosition(mesh);
  63395. var pos3 = this._bone1.getAbsolutePosition(mesh);
  63396. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  63397. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  63398. }
  63399. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  63400. this.maxAngle = Math.PI;
  63401. if (options) {
  63402. if (options.targetMesh) {
  63403. this.targetMesh = options.targetMesh;
  63404. this.targetMesh.computeWorldMatrix(true);
  63405. }
  63406. if (options.poleTargetMesh) {
  63407. this.poleTargetMesh = options.poleTargetMesh;
  63408. this.poleTargetMesh.computeWorldMatrix(true);
  63409. }
  63410. else if (options.poleTargetBone) {
  63411. this.poleTargetBone = options.poleTargetBone;
  63412. }
  63413. else if (this._bone1.getParent()) {
  63414. this.poleTargetBone = this._bone1.getParent();
  63415. }
  63416. if (options.poleTargetLocalOffset) {
  63417. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  63418. }
  63419. if (options.poleAngle) {
  63420. this.poleAngle = options.poleAngle;
  63421. }
  63422. if (options.bendAxis) {
  63423. this._bendAxis.copyFrom(options.bendAxis);
  63424. }
  63425. if (options.maxAngle) {
  63426. this.maxAngle = options.maxAngle;
  63427. }
  63428. if (options.slerpAmount) {
  63429. this.slerpAmount = options.slerpAmount;
  63430. }
  63431. }
  63432. }
  63433. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  63434. get: function () {
  63435. return this._maxAngle;
  63436. },
  63437. set: function (value) {
  63438. this._setMaxAngle(value);
  63439. },
  63440. enumerable: true,
  63441. configurable: true
  63442. });
  63443. BoneIKController.prototype._setMaxAngle = function (ang) {
  63444. if (ang < 0) {
  63445. ang = 0;
  63446. }
  63447. if (ang > Math.PI || ang == undefined) {
  63448. ang = Math.PI;
  63449. }
  63450. this._maxAngle = ang;
  63451. var a = this._bone1Length;
  63452. var b = this._bone2Length;
  63453. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  63454. };
  63455. BoneIKController.prototype.update = function () {
  63456. var bone1 = this._bone1;
  63457. if (!bone1) {
  63458. return;
  63459. }
  63460. var target = this.targetPosition;
  63461. var poleTarget = this.poleTargetPosition;
  63462. var mat1 = BoneIKController._tmpMats[0];
  63463. var mat2 = BoneIKController._tmpMats[1];
  63464. if (this.targetMesh) {
  63465. target.copyFrom(this.targetMesh.getAbsolutePosition());
  63466. }
  63467. if (this.poleTargetBone) {
  63468. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  63469. }
  63470. else if (this.poleTargetMesh) {
  63471. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  63472. }
  63473. var bonePos = BoneIKController._tmpVecs[0];
  63474. var zaxis = BoneIKController._tmpVecs[1];
  63475. var xaxis = BoneIKController._tmpVecs[2];
  63476. var yaxis = BoneIKController._tmpVecs[3];
  63477. var upAxis = BoneIKController._tmpVecs[4];
  63478. var _tmpQuat = BoneIKController._tmpQuat;
  63479. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  63480. poleTarget.subtractToRef(bonePos, upAxis);
  63481. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  63482. upAxis.y = 1;
  63483. }
  63484. else {
  63485. upAxis.normalize();
  63486. }
  63487. target.subtractToRef(bonePos, yaxis);
  63488. yaxis.normalize();
  63489. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  63490. zaxis.normalize();
  63491. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  63492. xaxis.normalize();
  63493. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  63494. var a = this._bone1Length;
  63495. var b = this._bone2Length;
  63496. var c = BABYLON.Vector3.Distance(bonePos, target);
  63497. if (this._maxReach > 0) {
  63498. c = Math.min(this._maxReach, c);
  63499. }
  63500. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  63501. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  63502. if (acosa > 1) {
  63503. acosa = 1;
  63504. }
  63505. if (acosb > 1) {
  63506. acosb = 1;
  63507. }
  63508. if (acosa < -1) {
  63509. acosa = -1;
  63510. }
  63511. if (acosb < -1) {
  63512. acosb = -1;
  63513. }
  63514. var angA = Math.acos(acosa);
  63515. var angB = Math.acos(acosb);
  63516. var angC = -angA - angB;
  63517. if (this._rightHandedSystem) {
  63518. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  63519. mat2.multiplyToRef(mat1, mat1);
  63520. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  63521. mat2.multiplyToRef(mat1, mat1);
  63522. }
  63523. else {
  63524. var _tmpVec = BoneIKController._tmpVecs[5];
  63525. _tmpVec.copyFrom(this._bendAxis);
  63526. _tmpVec.x *= -1;
  63527. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  63528. mat2.multiplyToRef(mat1, mat1);
  63529. }
  63530. if (this.poleAngle) {
  63531. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  63532. mat1.multiplyToRef(mat2, mat1);
  63533. }
  63534. if (this._bone1) {
  63535. if (this.slerpAmount < 1) {
  63536. if (!this._slerping) {
  63537. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  63538. }
  63539. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  63540. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  63541. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  63542. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  63543. this._slerping = true;
  63544. }
  63545. else {
  63546. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  63547. this._bone1Mat.copyFrom(mat1);
  63548. this._slerping = false;
  63549. }
  63550. }
  63551. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  63552. this._bone2Ang = angC;
  63553. };
  63554. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  63555. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  63556. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  63557. return BoneIKController;
  63558. }());
  63559. BABYLON.BoneIKController = BoneIKController;
  63560. })(BABYLON || (BABYLON = {}));
  63561. //# sourceMappingURL=babylon.boneIKController.js.map
  63562. var BABYLON;
  63563. (function (BABYLON) {
  63564. var BoneLookController = /** @class */ (function () {
  63565. /**
  63566. * Create a BoneLookController
  63567. * @param mesh the mesh that the bone belongs to
  63568. * @param bone the bone that will be looking to the target
  63569. * @param target the target Vector3 to look at
  63570. * @param settings optional settings:
  63571. * - maxYaw: the maximum angle the bone will yaw to
  63572. * - minYaw: the minimum angle the bone will yaw to
  63573. * - maxPitch: the maximum angle the bone will pitch to
  63574. * - minPitch: the minimum angle the bone will yaw to
  63575. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  63576. * - upAxis: the up axis of the coordinate system
  63577. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  63578. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  63579. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  63580. * - adjustYaw: used to make an adjustment to the yaw of the bone
  63581. * - adjustPitch: used to make an adjustment to the pitch of the bone
  63582. * - adjustRoll: used to make an adjustment to the roll of the bone
  63583. **/
  63584. function BoneLookController(mesh, bone, target, options) {
  63585. /**
  63586. * The up axis of the coordinate system that is used when the bone is rotated.
  63587. */
  63588. this.upAxis = BABYLON.Vector3.Up();
  63589. /**
  63590. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  63591. */
  63592. this.upAxisSpace = BABYLON.Space.LOCAL;
  63593. /**
  63594. * Used to make an adjustment to the yaw of the bone.
  63595. */
  63596. this.adjustYaw = 0;
  63597. /**
  63598. * Used to make an adjustment to the pitch of the bone.
  63599. */
  63600. this.adjustPitch = 0;
  63601. /**
  63602. * Used to make an adjustment to the roll of the bone.
  63603. */
  63604. this.adjustRoll = 0;
  63605. /**
  63606. * 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).
  63607. */
  63608. this.slerpAmount = 1;
  63609. this._boneQuat = BABYLON.Quaternion.Identity();
  63610. this._slerping = false;
  63611. this._firstFrameSkipped = false;
  63612. this._fowardAxis = BABYLON.Vector3.Forward();
  63613. this.mesh = mesh;
  63614. this.bone = bone;
  63615. this.target = target;
  63616. if (options) {
  63617. if (options.adjustYaw) {
  63618. this.adjustYaw = options.adjustYaw;
  63619. }
  63620. if (options.adjustPitch) {
  63621. this.adjustPitch = options.adjustPitch;
  63622. }
  63623. if (options.adjustRoll) {
  63624. this.adjustRoll = options.adjustRoll;
  63625. }
  63626. if (options.maxYaw != null) {
  63627. this.maxYaw = options.maxYaw;
  63628. }
  63629. else {
  63630. this.maxYaw = Math.PI;
  63631. }
  63632. if (options.minYaw != null) {
  63633. this.minYaw = options.minYaw;
  63634. }
  63635. else {
  63636. this.minYaw = -Math.PI;
  63637. }
  63638. if (options.maxPitch != null) {
  63639. this.maxPitch = options.maxPitch;
  63640. }
  63641. else {
  63642. this.maxPitch = Math.PI;
  63643. }
  63644. if (options.minPitch != null) {
  63645. this.minPitch = options.minPitch;
  63646. }
  63647. else {
  63648. this.minPitch = -Math.PI;
  63649. }
  63650. if (options.slerpAmount != null) {
  63651. this.slerpAmount = options.slerpAmount;
  63652. }
  63653. if (options.upAxis != null) {
  63654. this.upAxis = options.upAxis;
  63655. }
  63656. if (options.upAxisSpace != null) {
  63657. this.upAxisSpace = options.upAxisSpace;
  63658. }
  63659. if (options.yawAxis != null || options.pitchAxis != null) {
  63660. var newYawAxis = BABYLON.Axis.Y;
  63661. var newPitchAxis = BABYLON.Axis.X;
  63662. if (options.yawAxis != null) {
  63663. newYawAxis = options.yawAxis.clone();
  63664. newYawAxis.normalize();
  63665. }
  63666. if (options.pitchAxis != null) {
  63667. newPitchAxis = options.pitchAxis.clone();
  63668. newPitchAxis.normalize();
  63669. }
  63670. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  63671. this._transformYawPitch = BABYLON.Matrix.Identity();
  63672. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  63673. this._transformYawPitchInv = this._transformYawPitch.clone();
  63674. this._transformYawPitch.invert();
  63675. }
  63676. }
  63677. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  63678. this.upAxisSpace = BABYLON.Space.LOCAL;
  63679. }
  63680. }
  63681. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  63682. /**
  63683. * Get/set the minimum yaw angle that the bone can look to.
  63684. */
  63685. get: function () {
  63686. return this._minYaw;
  63687. },
  63688. set: function (value) {
  63689. this._minYaw = value;
  63690. this._minYawSin = Math.sin(value);
  63691. this._minYawCos = Math.cos(value);
  63692. if (this._maxYaw != null) {
  63693. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  63694. this._yawRange = this._maxYaw - this._minYaw;
  63695. }
  63696. },
  63697. enumerable: true,
  63698. configurable: true
  63699. });
  63700. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  63701. /**
  63702. * Get/set the maximum yaw angle that the bone can look to.
  63703. */
  63704. get: function () {
  63705. return this._maxYaw;
  63706. },
  63707. set: function (value) {
  63708. this._maxYaw = value;
  63709. this._maxYawSin = Math.sin(value);
  63710. this._maxYawCos = Math.cos(value);
  63711. if (this._minYaw != null) {
  63712. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  63713. this._yawRange = this._maxYaw - this._minYaw;
  63714. }
  63715. },
  63716. enumerable: true,
  63717. configurable: true
  63718. });
  63719. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  63720. /**
  63721. * Get/set the minimum pitch angle that the bone can look to.
  63722. */
  63723. get: function () {
  63724. return this._minPitch;
  63725. },
  63726. set: function (value) {
  63727. this._minPitch = value;
  63728. this._minPitchTan = Math.tan(value);
  63729. },
  63730. enumerable: true,
  63731. configurable: true
  63732. });
  63733. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  63734. /**
  63735. * Get/set the maximum pitch angle that the bone can look to.
  63736. */
  63737. get: function () {
  63738. return this._maxPitch;
  63739. },
  63740. set: function (value) {
  63741. this._maxPitch = value;
  63742. this._maxPitchTan = Math.tan(value);
  63743. },
  63744. enumerable: true,
  63745. configurable: true
  63746. });
  63747. /**
  63748. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  63749. */
  63750. BoneLookController.prototype.update = function () {
  63751. //skip the first frame when slerping so that the mesh rotation is correct
  63752. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  63753. this._firstFrameSkipped = true;
  63754. return;
  63755. }
  63756. var bone = this.bone;
  63757. var bonePos = BoneLookController._tmpVecs[0];
  63758. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  63759. var target = this.target;
  63760. var _tmpMat1 = BoneLookController._tmpMats[0];
  63761. var _tmpMat2 = BoneLookController._tmpMats[1];
  63762. var mesh = this.mesh;
  63763. var parentBone = bone.getParent();
  63764. var upAxis = BoneLookController._tmpVecs[1];
  63765. upAxis.copyFrom(this.upAxis);
  63766. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  63767. if (this._transformYawPitch) {
  63768. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  63769. }
  63770. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  63771. }
  63772. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  63773. mesh.getDirectionToRef(upAxis, upAxis);
  63774. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  63775. upAxis.normalize();
  63776. }
  63777. }
  63778. var checkYaw = false;
  63779. var checkPitch = false;
  63780. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  63781. checkYaw = true;
  63782. }
  63783. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  63784. checkPitch = true;
  63785. }
  63786. if (checkYaw || checkPitch) {
  63787. var spaceMat = BoneLookController._tmpMats[2];
  63788. var spaceMatInv = BoneLookController._tmpMats[3];
  63789. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  63790. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  63791. }
  63792. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  63793. spaceMat.copyFrom(mesh.getWorldMatrix());
  63794. }
  63795. else {
  63796. var forwardAxis = BoneLookController._tmpVecs[2];
  63797. forwardAxis.copyFrom(this._fowardAxis);
  63798. if (this._transformYawPitch) {
  63799. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  63800. }
  63801. if (parentBone) {
  63802. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  63803. }
  63804. else {
  63805. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  63806. }
  63807. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  63808. rightAxis.normalize();
  63809. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  63810. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  63811. }
  63812. spaceMat.invertToRef(spaceMatInv);
  63813. var xzlen = null;
  63814. if (checkPitch) {
  63815. var localTarget = BoneLookController._tmpVecs[3];
  63816. target.subtractToRef(bonePos, localTarget);
  63817. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  63818. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  63819. var pitch = Math.atan2(localTarget.y, xzlen);
  63820. var newPitch = pitch;
  63821. if (pitch > this._maxPitch) {
  63822. localTarget.y = this._maxPitchTan * xzlen;
  63823. newPitch = this._maxPitch;
  63824. }
  63825. else if (pitch < this._minPitch) {
  63826. localTarget.y = this._minPitchTan * xzlen;
  63827. newPitch = this._minPitch;
  63828. }
  63829. if (pitch != newPitch) {
  63830. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  63831. localTarget.addInPlace(bonePos);
  63832. target = localTarget;
  63833. }
  63834. }
  63835. if (checkYaw) {
  63836. var localTarget = BoneLookController._tmpVecs[4];
  63837. target.subtractToRef(bonePos, localTarget);
  63838. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  63839. var yaw = Math.atan2(localTarget.x, localTarget.z);
  63840. var newYaw = yaw;
  63841. if (yaw > this._maxYaw || yaw < this._minYaw) {
  63842. if (xzlen == null) {
  63843. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  63844. }
  63845. if (this._yawRange > Math.PI) {
  63846. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  63847. localTarget.z = this._maxYawCos * xzlen;
  63848. localTarget.x = this._maxYawSin * xzlen;
  63849. newYaw = this._maxYaw;
  63850. }
  63851. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  63852. localTarget.z = this._minYawCos * xzlen;
  63853. localTarget.x = this._minYawSin * xzlen;
  63854. newYaw = this._minYaw;
  63855. }
  63856. }
  63857. else {
  63858. if (yaw > this._maxYaw) {
  63859. localTarget.z = this._maxYawCos * xzlen;
  63860. localTarget.x = this._maxYawSin * xzlen;
  63861. newYaw = this._maxYaw;
  63862. }
  63863. else if (yaw < this._minYaw) {
  63864. localTarget.z = this._minYawCos * xzlen;
  63865. localTarget.x = this._minYawSin * xzlen;
  63866. newYaw = this._minYaw;
  63867. }
  63868. }
  63869. }
  63870. if (this._slerping && this._yawRange > Math.PI) {
  63871. //are we going to be crossing into the min/max region?
  63872. var boneFwd = BoneLookController._tmpVecs[8];
  63873. boneFwd.copyFrom(BABYLON.Axis.Z);
  63874. if (this._transformYawPitch) {
  63875. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  63876. }
  63877. var boneRotMat = BoneLookController._tmpMats[4];
  63878. this._boneQuat.toRotationMatrix(boneRotMat);
  63879. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  63880. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  63881. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  63882. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  63883. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  63884. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  63885. if (angBtwTar > angBtwMidYaw) {
  63886. if (xzlen == null) {
  63887. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  63888. }
  63889. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  63890. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  63891. if (angBtwMin < angBtwMax) {
  63892. newYaw = boneYaw + Math.PI * .75;
  63893. localTarget.z = Math.cos(newYaw) * xzlen;
  63894. localTarget.x = Math.sin(newYaw) * xzlen;
  63895. }
  63896. else {
  63897. newYaw = boneYaw - Math.PI * .75;
  63898. localTarget.z = Math.cos(newYaw) * xzlen;
  63899. localTarget.x = Math.sin(newYaw) * xzlen;
  63900. }
  63901. }
  63902. }
  63903. if (yaw != newYaw) {
  63904. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  63905. localTarget.addInPlace(bonePos);
  63906. target = localTarget;
  63907. }
  63908. }
  63909. }
  63910. var zaxis = BoneLookController._tmpVecs[5];
  63911. var xaxis = BoneLookController._tmpVecs[6];
  63912. var yaxis = BoneLookController._tmpVecs[7];
  63913. var _tmpQuat = BoneLookController._tmpQuat;
  63914. target.subtractToRef(bonePos, zaxis);
  63915. zaxis.normalize();
  63916. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  63917. xaxis.normalize();
  63918. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  63919. yaxis.normalize();
  63920. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  63921. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  63922. return;
  63923. }
  63924. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  63925. return;
  63926. }
  63927. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  63928. return;
  63929. }
  63930. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  63931. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  63932. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  63933. }
  63934. if (this.slerpAmount < 1) {
  63935. if (!this._slerping) {
  63936. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  63937. }
  63938. if (this._transformYawPitch) {
  63939. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  63940. }
  63941. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  63942. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  63943. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  63944. this._slerping = true;
  63945. }
  63946. else {
  63947. if (this._transformYawPitch) {
  63948. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  63949. }
  63950. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  63951. this._slerping = false;
  63952. }
  63953. };
  63954. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  63955. var angDiff = ang2 - ang1;
  63956. angDiff %= Math.PI * 2;
  63957. if (angDiff > Math.PI) {
  63958. angDiff -= Math.PI * 2;
  63959. }
  63960. else if (angDiff < -Math.PI) {
  63961. angDiff += Math.PI * 2;
  63962. }
  63963. return angDiff;
  63964. };
  63965. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  63966. ang1 %= (2 * Math.PI);
  63967. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  63968. ang2 %= (2 * Math.PI);
  63969. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  63970. var ab = 0;
  63971. if (ang1 < ang2) {
  63972. ab = ang2 - ang1;
  63973. }
  63974. else {
  63975. ab = ang1 - ang2;
  63976. }
  63977. if (ab > Math.PI) {
  63978. ab = Math.PI * 2 - ab;
  63979. }
  63980. return ab;
  63981. };
  63982. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  63983. ang %= (2 * Math.PI);
  63984. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  63985. ang1 %= (2 * Math.PI);
  63986. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  63987. ang2 %= (2 * Math.PI);
  63988. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  63989. if (ang1 < ang2) {
  63990. if (ang > ang1 && ang < ang2) {
  63991. return true;
  63992. }
  63993. }
  63994. else {
  63995. if (ang > ang2 && ang < ang1) {
  63996. return true;
  63997. }
  63998. }
  63999. return false;
  64000. };
  64001. 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()];
  64002. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  64003. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  64004. return BoneLookController;
  64005. }());
  64006. BABYLON.BoneLookController = BoneLookController;
  64007. })(BABYLON || (BABYLON = {}));
  64008. //# sourceMappingURL=babylon.boneLookController.js.map
  64009. var BABYLON;
  64010. (function (BABYLON) {
  64011. var Skeleton = /** @class */ (function () {
  64012. function Skeleton(name, id, scene) {
  64013. this.name = name;
  64014. this.id = id;
  64015. this.bones = new Array();
  64016. this.needInitialSkinMatrix = false;
  64017. this._isDirty = true;
  64018. this._meshesWithPoseMatrix = new Array();
  64019. this._identity = BABYLON.Matrix.Identity();
  64020. this._ranges = {};
  64021. this._lastAbsoluteTransformsUpdateId = -1;
  64022. // Events
  64023. /**
  64024. * An event triggered before computing the skeleton's matrices
  64025. * @type {BABYLON.Observable}
  64026. */
  64027. this.onBeforeComputeObservable = new BABYLON.Observable();
  64028. this.bones = [];
  64029. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  64030. scene.skeletons.push(this);
  64031. //make sure it will recalculate the matrix next time prepare is called.
  64032. this._isDirty = true;
  64033. }
  64034. // Members
  64035. Skeleton.prototype.getTransformMatrices = function (mesh) {
  64036. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  64037. return mesh._bonesTransformMatrices;
  64038. }
  64039. if (!this._transformMatrices) {
  64040. this.prepare();
  64041. }
  64042. return this._transformMatrices;
  64043. };
  64044. Skeleton.prototype.getScene = function () {
  64045. return this._scene;
  64046. };
  64047. // Methods
  64048. /**
  64049. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  64050. */
  64051. Skeleton.prototype.toString = function (fullDetails) {
  64052. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  64053. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  64054. if (fullDetails) {
  64055. ret += ", Ranges: {";
  64056. var first = true;
  64057. for (var name_1 in this._ranges) {
  64058. if (first) {
  64059. ret += ", ";
  64060. first = false;
  64061. }
  64062. ret += name_1;
  64063. }
  64064. ret += "}";
  64065. }
  64066. return ret;
  64067. };
  64068. /**
  64069. * Get bone's index searching by name
  64070. * @param {string} name is bone's name to search for
  64071. * @return {number} Indice of the bone. Returns -1 if not found
  64072. */
  64073. Skeleton.prototype.getBoneIndexByName = function (name) {
  64074. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  64075. if (this.bones[boneIndex].name === name) {
  64076. return boneIndex;
  64077. }
  64078. }
  64079. return -1;
  64080. };
  64081. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  64082. // check name not already in use
  64083. if (!this._ranges[name]) {
  64084. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  64085. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  64086. if (this.bones[i].animations[0]) {
  64087. this.bones[i].animations[0].createRange(name, from, to);
  64088. }
  64089. }
  64090. }
  64091. };
  64092. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  64093. if (deleteFrames === void 0) { deleteFrames = true; }
  64094. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  64095. if (this.bones[i].animations[0]) {
  64096. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  64097. }
  64098. }
  64099. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  64100. };
  64101. Skeleton.prototype.getAnimationRange = function (name) {
  64102. return this._ranges[name];
  64103. };
  64104. /**
  64105. * Returns as an Array, all AnimationRanges defined on this skeleton
  64106. */
  64107. Skeleton.prototype.getAnimationRanges = function () {
  64108. var animationRanges = [];
  64109. var name;
  64110. var i = 0;
  64111. for (name in this._ranges) {
  64112. animationRanges[i] = this._ranges[name];
  64113. i++;
  64114. }
  64115. return animationRanges;
  64116. };
  64117. /**
  64118. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  64119. */
  64120. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  64121. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  64122. if (this._ranges[name] || !source.getAnimationRange(name)) {
  64123. return false;
  64124. }
  64125. var ret = true;
  64126. var frameOffset = this._getHighestAnimationFrame() + 1;
  64127. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  64128. var boneDict = {};
  64129. var sourceBones = source.bones;
  64130. var nBones;
  64131. var i;
  64132. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  64133. boneDict[sourceBones[i].name] = sourceBones[i];
  64134. }
  64135. if (this.bones.length !== sourceBones.length) {
  64136. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  64137. ret = false;
  64138. }
  64139. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  64140. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  64141. var boneName = this.bones[i].name;
  64142. var sourceBone = boneDict[boneName];
  64143. if (sourceBone) {
  64144. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  64145. }
  64146. else {
  64147. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  64148. ret = false;
  64149. }
  64150. }
  64151. // do not call createAnimationRange(), since it also is done to bones, which was already done
  64152. var range = source.getAnimationRange(name);
  64153. if (range) {
  64154. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  64155. }
  64156. return ret;
  64157. };
  64158. Skeleton.prototype.returnToRest = function () {
  64159. for (var index = 0; index < this.bones.length; index++) {
  64160. this.bones[index].returnToRest();
  64161. }
  64162. };
  64163. Skeleton.prototype._getHighestAnimationFrame = function () {
  64164. var ret = 0;
  64165. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  64166. if (this.bones[i].animations[0]) {
  64167. var highest = this.bones[i].animations[0].getHighestFrame();
  64168. if (ret < highest) {
  64169. ret = highest;
  64170. }
  64171. }
  64172. }
  64173. return ret;
  64174. };
  64175. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  64176. var range = this.getAnimationRange(name);
  64177. if (!range) {
  64178. return null;
  64179. }
  64180. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  64181. };
  64182. Skeleton.prototype._markAsDirty = function () {
  64183. this._isDirty = true;
  64184. };
  64185. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  64186. this._meshesWithPoseMatrix.push(mesh);
  64187. };
  64188. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  64189. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  64190. if (index > -1) {
  64191. this._meshesWithPoseMatrix.splice(index, 1);
  64192. }
  64193. };
  64194. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  64195. this.onBeforeComputeObservable.notifyObservers(this);
  64196. for (var index = 0; index < this.bones.length; index++) {
  64197. var bone = this.bones[index];
  64198. var parentBone = bone.getParent();
  64199. if (parentBone) {
  64200. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  64201. }
  64202. else {
  64203. if (initialSkinMatrix) {
  64204. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  64205. }
  64206. else {
  64207. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  64208. }
  64209. }
  64210. if (bone._index !== -1) {
  64211. var mappedIndex = bone._index === null ? index : bone._index;
  64212. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  64213. }
  64214. }
  64215. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  64216. };
  64217. Skeleton.prototype.prepare = function () {
  64218. if (!this._isDirty) {
  64219. return;
  64220. }
  64221. if (this.needInitialSkinMatrix) {
  64222. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  64223. var mesh = this._meshesWithPoseMatrix[index];
  64224. var poseMatrix = mesh.getPoseMatrix();
  64225. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  64226. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  64227. }
  64228. if (this._synchronizedWithMesh !== mesh) {
  64229. this._synchronizedWithMesh = mesh;
  64230. // Prepare bones
  64231. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  64232. var bone = this.bones[boneIndex];
  64233. if (!bone.getParent()) {
  64234. var matrix = bone.getBaseMatrix();
  64235. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  64236. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  64237. }
  64238. }
  64239. }
  64240. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  64241. }
  64242. }
  64243. else {
  64244. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  64245. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  64246. }
  64247. this._computeTransformMatrices(this._transformMatrices, null);
  64248. }
  64249. this._isDirty = false;
  64250. this._scene._activeBones.addCount(this.bones.length, false);
  64251. };
  64252. Skeleton.prototype.getAnimatables = function () {
  64253. if (!this._animatables || this._animatables.length !== this.bones.length) {
  64254. this._animatables = [];
  64255. for (var index = 0; index < this.bones.length; index++) {
  64256. this._animatables.push(this.bones[index]);
  64257. }
  64258. }
  64259. return this._animatables;
  64260. };
  64261. Skeleton.prototype.clone = function (name, id) {
  64262. var result = new Skeleton(name, id || name, this._scene);
  64263. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  64264. for (var index = 0; index < this.bones.length; index++) {
  64265. var source = this.bones[index];
  64266. var parentBone = null;
  64267. var parent_1 = source.getParent();
  64268. if (parent_1) {
  64269. var parentIndex = this.bones.indexOf(parent_1);
  64270. parentBone = result.bones[parentIndex];
  64271. }
  64272. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  64273. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  64274. }
  64275. if (this._ranges) {
  64276. result._ranges = {};
  64277. for (var rangeName in this._ranges) {
  64278. var range = this._ranges[rangeName];
  64279. if (range) {
  64280. result._ranges[rangeName] = range.clone();
  64281. }
  64282. }
  64283. }
  64284. this._isDirty = true;
  64285. return result;
  64286. };
  64287. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  64288. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  64289. this.bones.forEach(function (bone) {
  64290. bone.animations.forEach(function (animation) {
  64291. animation.enableBlending = true;
  64292. animation.blendingSpeed = blendingSpeed;
  64293. });
  64294. });
  64295. };
  64296. Skeleton.prototype.dispose = function () {
  64297. this._meshesWithPoseMatrix = [];
  64298. // Animations
  64299. this.getScene().stopAnimation(this);
  64300. // Remove from scene
  64301. this.getScene().removeSkeleton(this);
  64302. };
  64303. Skeleton.prototype.serialize = function () {
  64304. var serializationObject = {};
  64305. serializationObject.name = this.name;
  64306. serializationObject.id = this.id;
  64307. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  64308. serializationObject.bones = [];
  64309. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  64310. for (var index = 0; index < this.bones.length; index++) {
  64311. var bone = this.bones[index];
  64312. var parent_2 = bone.getParent();
  64313. var serializedBone = {
  64314. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  64315. name: bone.name,
  64316. matrix: bone.getBaseMatrix().toArray(),
  64317. rest: bone.getRestPose().toArray()
  64318. };
  64319. serializationObject.bones.push(serializedBone);
  64320. if (bone.length) {
  64321. serializedBone.length = bone.length;
  64322. }
  64323. if (bone.animations && bone.animations.length > 0) {
  64324. serializedBone.animation = bone.animations[0].serialize();
  64325. }
  64326. serializationObject.ranges = [];
  64327. for (var name in this._ranges) {
  64328. var source = this._ranges[name];
  64329. if (!source) {
  64330. continue;
  64331. }
  64332. var range = {};
  64333. range.name = name;
  64334. range.from = source.from;
  64335. range.to = source.to;
  64336. serializationObject.ranges.push(range);
  64337. }
  64338. }
  64339. return serializationObject;
  64340. };
  64341. Skeleton.Parse = function (parsedSkeleton, scene) {
  64342. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  64343. if (parsedSkeleton.dimensionsAtRest) {
  64344. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  64345. }
  64346. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  64347. var index;
  64348. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  64349. var parsedBone = parsedSkeleton.bones[index];
  64350. var parentBone = null;
  64351. if (parsedBone.parentBoneIndex > -1) {
  64352. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  64353. }
  64354. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  64355. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  64356. if (parsedBone.length) {
  64357. bone.length = parsedBone.length;
  64358. }
  64359. if (parsedBone.animation) {
  64360. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  64361. }
  64362. }
  64363. // placed after bones, so createAnimationRange can cascade down
  64364. if (parsedSkeleton.ranges) {
  64365. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  64366. var data = parsedSkeleton.ranges[index];
  64367. skeleton.createAnimationRange(data.name, data.from, data.to);
  64368. }
  64369. }
  64370. return skeleton;
  64371. };
  64372. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  64373. if (forceUpdate === void 0) { forceUpdate = false; }
  64374. var renderId = this._scene.getRenderId();
  64375. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  64376. this.bones[0].computeAbsoluteTransforms();
  64377. this._lastAbsoluteTransformsUpdateId = renderId;
  64378. }
  64379. };
  64380. Skeleton.prototype.getPoseMatrix = function () {
  64381. var poseMatrix = null;
  64382. if (this._meshesWithPoseMatrix.length > 0) {
  64383. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  64384. }
  64385. return poseMatrix;
  64386. };
  64387. Skeleton.prototype.sortBones = function () {
  64388. var bones = new Array();
  64389. var visited = new Array(this.bones.length);
  64390. for (var index = 0; index < this.bones.length; index++) {
  64391. this._sortBones(index, bones, visited);
  64392. }
  64393. this.bones = bones;
  64394. };
  64395. Skeleton.prototype._sortBones = function (index, bones, visited) {
  64396. if (visited[index]) {
  64397. return;
  64398. }
  64399. visited[index] = true;
  64400. var bone = this.bones[index];
  64401. if (bone._index === undefined) {
  64402. bone._index = index;
  64403. }
  64404. var parentBone = bone.getParent();
  64405. if (parentBone) {
  64406. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  64407. }
  64408. bones.push(bone);
  64409. };
  64410. return Skeleton;
  64411. }());
  64412. BABYLON.Skeleton = Skeleton;
  64413. })(BABYLON || (BABYLON = {}));
  64414. //# sourceMappingURL=babylon.skeleton.js.map
  64415. var BABYLON;
  64416. (function (BABYLON) {
  64417. var SphericalPolynomial = /** @class */ (function () {
  64418. function SphericalPolynomial() {
  64419. this.x = BABYLON.Vector3.Zero();
  64420. this.y = BABYLON.Vector3.Zero();
  64421. this.z = BABYLON.Vector3.Zero();
  64422. this.xx = BABYLON.Vector3.Zero();
  64423. this.yy = BABYLON.Vector3.Zero();
  64424. this.zz = BABYLON.Vector3.Zero();
  64425. this.xy = BABYLON.Vector3.Zero();
  64426. this.yz = BABYLON.Vector3.Zero();
  64427. this.zx = BABYLON.Vector3.Zero();
  64428. }
  64429. SphericalPolynomial.prototype.addAmbient = function (color) {
  64430. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  64431. this.xx = this.xx.add(colorVector);
  64432. this.yy = this.yy.add(colorVector);
  64433. this.zz = this.zz.add(colorVector);
  64434. };
  64435. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  64436. var result = new SphericalPolynomial();
  64437. result.x = harmonics.L11.scale(1.02333);
  64438. result.y = harmonics.L1_1.scale(1.02333);
  64439. result.z = harmonics.L10.scale(1.02333);
  64440. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  64441. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  64442. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  64443. result.yz = harmonics.L2_1.scale(0.858086);
  64444. result.zx = harmonics.L21.scale(0.858086);
  64445. result.xy = harmonics.L2_2.scale(0.858086);
  64446. result.scale(1.0 / Math.PI);
  64447. return result;
  64448. };
  64449. SphericalPolynomial.prototype.scale = function (scale) {
  64450. this.x = this.x.scale(scale);
  64451. this.y = this.y.scale(scale);
  64452. this.z = this.z.scale(scale);
  64453. this.xx = this.xx.scale(scale);
  64454. this.yy = this.yy.scale(scale);
  64455. this.zz = this.zz.scale(scale);
  64456. this.yz = this.yz.scale(scale);
  64457. this.zx = this.zx.scale(scale);
  64458. this.xy = this.xy.scale(scale);
  64459. };
  64460. return SphericalPolynomial;
  64461. }());
  64462. BABYLON.SphericalPolynomial = SphericalPolynomial;
  64463. var SphericalHarmonics = /** @class */ (function () {
  64464. function SphericalHarmonics() {
  64465. this.L00 = BABYLON.Vector3.Zero();
  64466. this.L1_1 = BABYLON.Vector3.Zero();
  64467. this.L10 = BABYLON.Vector3.Zero();
  64468. this.L11 = BABYLON.Vector3.Zero();
  64469. this.L2_2 = BABYLON.Vector3.Zero();
  64470. this.L2_1 = BABYLON.Vector3.Zero();
  64471. this.L20 = BABYLON.Vector3.Zero();
  64472. this.L21 = BABYLON.Vector3.Zero();
  64473. this.L22 = BABYLON.Vector3.Zero();
  64474. }
  64475. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  64476. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  64477. var c = colorVector.scale(deltaSolidAngle);
  64478. this.L00 = this.L00.add(c.scale(0.282095));
  64479. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  64480. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  64481. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  64482. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  64483. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  64484. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  64485. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  64486. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  64487. };
  64488. SphericalHarmonics.prototype.scale = function (scale) {
  64489. this.L00 = this.L00.scale(scale);
  64490. this.L1_1 = this.L1_1.scale(scale);
  64491. this.L10 = this.L10.scale(scale);
  64492. this.L11 = this.L11.scale(scale);
  64493. this.L2_2 = this.L2_2.scale(scale);
  64494. this.L2_1 = this.L2_1.scale(scale);
  64495. this.L20 = this.L20.scale(scale);
  64496. this.L21 = this.L21.scale(scale);
  64497. this.L22 = this.L22.scale(scale);
  64498. };
  64499. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  64500. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  64501. //
  64502. // E_lm = A_l * L_lm
  64503. //
  64504. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  64505. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  64506. // the scaling factors are given in equation 9.
  64507. // Constant (Band 0)
  64508. this.L00 = this.L00.scale(3.141593);
  64509. // Linear (Band 1)
  64510. this.L1_1 = this.L1_1.scale(2.094395);
  64511. this.L10 = this.L10.scale(2.094395);
  64512. this.L11 = this.L11.scale(2.094395);
  64513. // Quadratic (Band 2)
  64514. this.L2_2 = this.L2_2.scale(0.785398);
  64515. this.L2_1 = this.L2_1.scale(0.785398);
  64516. this.L20 = this.L20.scale(0.785398);
  64517. this.L21 = this.L21.scale(0.785398);
  64518. this.L22 = this.L22.scale(0.785398);
  64519. };
  64520. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  64521. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  64522. // L = (1/pi) * E * rho
  64523. //
  64524. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  64525. this.scale(1.0 / Math.PI);
  64526. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  64527. // (The pixel shader must apply albedo after texture fetches, etc).
  64528. };
  64529. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  64530. var result = new SphericalHarmonics();
  64531. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  64532. result.L1_1 = polynomial.y.scale(0.977204);
  64533. result.L10 = polynomial.z.scale(0.977204);
  64534. result.L11 = polynomial.x.scale(0.977204);
  64535. result.L2_2 = polynomial.xy.scale(1.16538);
  64536. result.L2_1 = polynomial.yz.scale(1.16538);
  64537. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  64538. result.L21 = polynomial.zx.scale(1.16538);
  64539. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  64540. result.scale(Math.PI);
  64541. return result;
  64542. };
  64543. return SphericalHarmonics;
  64544. }());
  64545. BABYLON.SphericalHarmonics = SphericalHarmonics;
  64546. })(BABYLON || (BABYLON = {}));
  64547. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  64548. var BABYLON;
  64549. (function (BABYLON) {
  64550. var Internals;
  64551. (function (Internals) {
  64552. var FileFaceOrientation = /** @class */ (function () {
  64553. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  64554. this.name = name;
  64555. this.worldAxisForNormal = worldAxisForNormal;
  64556. this.worldAxisForFileX = worldAxisForFileX;
  64557. this.worldAxisForFileY = worldAxisForFileY;
  64558. }
  64559. return FileFaceOrientation;
  64560. }());
  64561. ;
  64562. /**
  64563. * Helper class dealing with the extraction of spherical polynomial dataArray
  64564. * from a cube map.
  64565. */
  64566. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  64567. function CubeMapToSphericalPolynomialTools() {
  64568. }
  64569. /**
  64570. * Converts a texture to the according Spherical Polynomial data.
  64571. * This extracts the first 3 orders only as they are the only one used in the lighting.
  64572. *
  64573. * @param texture The texture to extract the information from.
  64574. * @return The Spherical Polynomial data.
  64575. */
  64576. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  64577. if (!texture.isCube) {
  64578. // Only supports cube Textures currently.
  64579. return null;
  64580. }
  64581. var size = texture.getSize().width;
  64582. var right = texture.readPixels(0);
  64583. var left = texture.readPixels(1);
  64584. var up;
  64585. var down;
  64586. if (texture.isRenderTarget) {
  64587. up = texture.readPixels(3);
  64588. down = texture.readPixels(2);
  64589. }
  64590. else {
  64591. up = texture.readPixels(2);
  64592. down = texture.readPixels(3);
  64593. }
  64594. var front = texture.readPixels(4);
  64595. var back = texture.readPixels(5);
  64596. var gammaSpace = texture.gammaSpace;
  64597. // Always read as RGBA.
  64598. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  64599. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  64600. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  64601. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  64602. }
  64603. var cubeInfo = {
  64604. size: size,
  64605. right: right,
  64606. left: left,
  64607. up: up,
  64608. down: down,
  64609. front: front,
  64610. back: back,
  64611. format: format,
  64612. type: type,
  64613. gammaSpace: gammaSpace,
  64614. };
  64615. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  64616. };
  64617. /**
  64618. * Converts a cubemap to the according Spherical Polynomial data.
  64619. * This extracts the first 3 orders only as they are the only one used in the lighting.
  64620. *
  64621. * @param cubeInfo The Cube map to extract the information from.
  64622. * @return The Spherical Polynomial data.
  64623. */
  64624. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  64625. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  64626. var totalSolidAngle = 0.0;
  64627. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  64628. var du = 2.0 / cubeInfo.size;
  64629. var dv = du;
  64630. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  64631. var minUV = du * 0.5 - 1.0;
  64632. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  64633. var fileFace = this.FileFaces[faceIndex];
  64634. var dataArray = cubeInfo[fileFace.name];
  64635. var v = minUV;
  64636. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  64637. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  64638. // Because SP is still linear, so summation is fine in that basis.
  64639. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  64640. for (var y = 0; y < cubeInfo.size; y++) {
  64641. var u = minUV;
  64642. for (var x = 0; x < cubeInfo.size; x++) {
  64643. // World direction (not normalised)
  64644. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  64645. worldDirection.normalize();
  64646. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  64647. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  64648. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  64649. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  64650. // Handle Integer types.
  64651. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  64652. r /= 255;
  64653. g /= 255;
  64654. b /= 255;
  64655. }
  64656. // Handle Gamma space textures.
  64657. if (cubeInfo.gammaSpace) {
  64658. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  64659. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  64660. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  64661. }
  64662. var color = new BABYLON.Color3(r, g, b);
  64663. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  64664. totalSolidAngle += deltaSolidAngle;
  64665. u += du;
  64666. }
  64667. v += dv;
  64668. }
  64669. }
  64670. // Solid angle for entire sphere is 4*pi
  64671. var sphereSolidAngle = 4.0 * Math.PI;
  64672. // Adjust the solid angle to allow for how many faces we processed.
  64673. var facesProcessed = 6.0;
  64674. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  64675. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  64676. // This is needed because the numerical integration over the cube uses a
  64677. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  64678. // and also to compensate for accumulative error due to float precision in the summation.
  64679. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  64680. sphericalHarmonics.scale(correctionFactor);
  64681. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  64682. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  64683. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  64684. };
  64685. CubeMapToSphericalPolynomialTools.FileFaces = [
  64686. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  64687. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  64688. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  64689. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  64690. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  64691. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  64692. ];
  64693. return CubeMapToSphericalPolynomialTools;
  64694. }());
  64695. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  64696. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  64697. })(BABYLON || (BABYLON = {}));
  64698. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  64699. var BABYLON;
  64700. (function (BABYLON) {
  64701. var Internals;
  64702. (function (Internals) {
  64703. /**
  64704. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  64705. */
  64706. var PanoramaToCubeMapTools = /** @class */ (function () {
  64707. function PanoramaToCubeMapTools() {
  64708. }
  64709. /**
  64710. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  64711. *
  64712. * @param float32Array The source data.
  64713. * @param inputWidth The width of the input panorama.
  64714. * @param inputhHeight The height of the input panorama.
  64715. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  64716. * @return The cubemap data
  64717. */
  64718. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  64719. if (!float32Array) {
  64720. throw "ConvertPanoramaToCubemap: input cannot be null";
  64721. }
  64722. if (float32Array.length != inputWidth * inputHeight * 3) {
  64723. throw "ConvertPanoramaToCubemap: input size is wrong";
  64724. }
  64725. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  64726. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  64727. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  64728. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  64729. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  64730. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  64731. return {
  64732. front: textureFront,
  64733. back: textureBack,
  64734. left: textureLeft,
  64735. right: textureRight,
  64736. up: textureUp,
  64737. down: textureDown,
  64738. size: size,
  64739. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  64740. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  64741. gammaSpace: false,
  64742. };
  64743. };
  64744. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  64745. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  64746. var textureArray = new Float32Array(buffer);
  64747. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  64748. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  64749. var dy = 1 / texSize;
  64750. var fy = 0;
  64751. for (var y = 0; y < texSize; y++) {
  64752. var xv1 = faceData[0];
  64753. var xv2 = faceData[2];
  64754. for (var x = 0; x < texSize; x++) {
  64755. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  64756. v.normalize();
  64757. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  64758. // 3 channels per pixels
  64759. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  64760. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  64761. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  64762. xv1 = xv1.add(rotDX1);
  64763. xv2 = xv2.add(rotDX2);
  64764. }
  64765. fy += dy;
  64766. }
  64767. return textureArray;
  64768. };
  64769. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  64770. var theta = Math.atan2(vDir.z, vDir.x);
  64771. var phi = Math.acos(vDir.y);
  64772. while (theta < -Math.PI)
  64773. theta += 2 * Math.PI;
  64774. while (theta > Math.PI)
  64775. theta -= 2 * Math.PI;
  64776. var dx = theta / Math.PI;
  64777. var dy = phi / Math.PI;
  64778. // recenter.
  64779. dx = dx * 0.5 + 0.5;
  64780. var px = Math.round(dx * inputWidth);
  64781. if (px < 0)
  64782. px = 0;
  64783. else if (px >= inputWidth)
  64784. px = inputWidth - 1;
  64785. var py = Math.round(dy * inputHeight);
  64786. if (py < 0)
  64787. py = 0;
  64788. else if (py >= inputHeight)
  64789. py = inputHeight - 1;
  64790. var inputY = (inputHeight - py - 1);
  64791. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  64792. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  64793. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  64794. return {
  64795. r: r,
  64796. g: g,
  64797. b: b
  64798. };
  64799. };
  64800. PanoramaToCubeMapTools.FACE_FRONT = [
  64801. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  64802. new BABYLON.Vector3(1.0, -1.0, -1.0),
  64803. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  64804. new BABYLON.Vector3(1.0, 1.0, -1.0)
  64805. ];
  64806. PanoramaToCubeMapTools.FACE_BACK = [
  64807. new BABYLON.Vector3(1.0, -1.0, 1.0),
  64808. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  64809. new BABYLON.Vector3(1.0, 1.0, 1.0),
  64810. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  64811. ];
  64812. PanoramaToCubeMapTools.FACE_RIGHT = [
  64813. new BABYLON.Vector3(1.0, -1.0, -1.0),
  64814. new BABYLON.Vector3(1.0, -1.0, 1.0),
  64815. new BABYLON.Vector3(1.0, 1.0, -1.0),
  64816. new BABYLON.Vector3(1.0, 1.0, 1.0)
  64817. ];
  64818. PanoramaToCubeMapTools.FACE_LEFT = [
  64819. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  64820. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  64821. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  64822. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  64823. ];
  64824. PanoramaToCubeMapTools.FACE_DOWN = [
  64825. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  64826. new BABYLON.Vector3(1.0, 1.0, -1.0),
  64827. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  64828. new BABYLON.Vector3(1.0, 1.0, 1.0)
  64829. ];
  64830. PanoramaToCubeMapTools.FACE_UP = [
  64831. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  64832. new BABYLON.Vector3(1.0, -1.0, 1.0),
  64833. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  64834. new BABYLON.Vector3(1.0, -1.0, -1.0)
  64835. ];
  64836. return PanoramaToCubeMapTools;
  64837. }());
  64838. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  64839. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  64840. })(BABYLON || (BABYLON = {}));
  64841. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  64842. var BABYLON;
  64843. (function (BABYLON) {
  64844. var Internals;
  64845. (function (Internals) {
  64846. ;
  64847. /**
  64848. * This groups tools to convert HDR texture to native colors array.
  64849. */
  64850. var HDRTools = /** @class */ (function () {
  64851. function HDRTools() {
  64852. }
  64853. HDRTools.Ldexp = function (mantissa, exponent) {
  64854. if (exponent > 1023) {
  64855. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  64856. }
  64857. if (exponent < -1074) {
  64858. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  64859. }
  64860. return mantissa * Math.pow(2, exponent);
  64861. };
  64862. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  64863. if (exponent > 0) {
  64864. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  64865. float32array[index + 0] = red * exponent;
  64866. float32array[index + 1] = green * exponent;
  64867. float32array[index + 2] = blue * exponent;
  64868. }
  64869. else {
  64870. float32array[index + 0] = 0;
  64871. float32array[index + 1] = 0;
  64872. float32array[index + 2] = 0;
  64873. }
  64874. };
  64875. HDRTools.readStringLine = function (uint8array, startIndex) {
  64876. var line = "";
  64877. var character = "";
  64878. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  64879. character = String.fromCharCode(uint8array[i]);
  64880. if (character == "\n") {
  64881. break;
  64882. }
  64883. line += character;
  64884. }
  64885. return line;
  64886. };
  64887. /**
  64888. * Reads header information from an RGBE texture stored in a native array.
  64889. * More information on this format are available here:
  64890. * https://en.wikipedia.org/wiki/RGBE_image_format
  64891. *
  64892. * @param uint8array The binary file stored in native array.
  64893. * @return The header information.
  64894. */
  64895. HDRTools.RGBE_ReadHeader = function (uint8array) {
  64896. var height = 0;
  64897. var width = 0;
  64898. var line = this.readStringLine(uint8array, 0);
  64899. if (line[0] != '#' || line[1] != '?') {
  64900. throw "Bad HDR Format.";
  64901. }
  64902. var endOfHeader = false;
  64903. var findFormat = false;
  64904. var lineIndex = 0;
  64905. do {
  64906. lineIndex += (line.length + 1);
  64907. line = this.readStringLine(uint8array, lineIndex);
  64908. if (line == "FORMAT=32-bit_rle_rgbe") {
  64909. findFormat = true;
  64910. }
  64911. else if (line.length == 0) {
  64912. endOfHeader = true;
  64913. }
  64914. } while (!endOfHeader);
  64915. if (!findFormat) {
  64916. throw "HDR Bad header format, unsupported FORMAT";
  64917. }
  64918. lineIndex += (line.length + 1);
  64919. line = this.readStringLine(uint8array, lineIndex);
  64920. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  64921. var match = sizeRegexp.exec(line);
  64922. // TODO. Support +Y and -X if needed.
  64923. if (!match || match.length < 3) {
  64924. throw "HDR Bad header format, no size";
  64925. }
  64926. width = parseInt(match[2]);
  64927. height = parseInt(match[1]);
  64928. if (width < 8 || width > 0x7fff) {
  64929. throw "HDR Bad header format, unsupported size";
  64930. }
  64931. lineIndex += (line.length + 1);
  64932. return {
  64933. height: height,
  64934. width: width,
  64935. dataPosition: lineIndex
  64936. };
  64937. };
  64938. /**
  64939. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  64940. * This RGBE texture needs to store the information as a panorama.
  64941. *
  64942. * More information on this format are available here:
  64943. * https://en.wikipedia.org/wiki/RGBE_image_format
  64944. *
  64945. * @param buffer The binary file stored in an array buffer.
  64946. * @param size The expected size of the extracted cubemap.
  64947. * @return The Cube Map information.
  64948. */
  64949. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  64950. var uint8array = new Uint8Array(buffer);
  64951. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  64952. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  64953. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  64954. return cubeMapData;
  64955. };
  64956. /**
  64957. * Returns the pixels data extracted from an RGBE texture.
  64958. * This pixels will be stored left to right up to down in the R G B order in one array.
  64959. *
  64960. * More information on this format are available here:
  64961. * https://en.wikipedia.org/wiki/RGBE_image_format
  64962. *
  64963. * @param uint8array The binary file stored in an array buffer.
  64964. * @param hdrInfo The header information of the file.
  64965. * @return The pixels data in RGB right to left up to down order.
  64966. */
  64967. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  64968. // Keep for multi format supports.
  64969. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  64970. };
  64971. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  64972. var num_scanlines = hdrInfo.height;
  64973. var scanline_width = hdrInfo.width;
  64974. var a, b, c, d, count;
  64975. var dataIndex = hdrInfo.dataPosition;
  64976. var index = 0, endIndex = 0, i = 0;
  64977. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  64978. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  64979. // 3 channels of 4 bytes per pixel in float.
  64980. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  64981. var resultArray = new Float32Array(resultBuffer);
  64982. // read in each successive scanline
  64983. while (num_scanlines > 0) {
  64984. a = uint8array[dataIndex++];
  64985. b = uint8array[dataIndex++];
  64986. c = uint8array[dataIndex++];
  64987. d = uint8array[dataIndex++];
  64988. if (a != 2 || b != 2 || (c & 0x80)) {
  64989. // this file is not run length encoded
  64990. throw "HDR Bad header format, not RLE";
  64991. }
  64992. if (((c << 8) | d) != scanline_width) {
  64993. throw "HDR Bad header format, wrong scan line width";
  64994. }
  64995. index = 0;
  64996. // read each of the four channels for the scanline into the buffer
  64997. for (i = 0; i < 4; i++) {
  64998. endIndex = (i + 1) * scanline_width;
  64999. while (index < endIndex) {
  65000. a = uint8array[dataIndex++];
  65001. b = uint8array[dataIndex++];
  65002. if (a > 128) {
  65003. // a run of the same value
  65004. count = a - 128;
  65005. if ((count == 0) || (count > endIndex - index)) {
  65006. throw "HDR Bad Format, bad scanline data (run)";
  65007. }
  65008. while (count-- > 0) {
  65009. scanLineArray[index++] = b;
  65010. }
  65011. }
  65012. else {
  65013. // a non-run
  65014. count = a;
  65015. if ((count == 0) || (count > endIndex - index)) {
  65016. throw "HDR Bad Format, bad scanline data (non-run)";
  65017. }
  65018. scanLineArray[index++] = b;
  65019. if (--count > 0) {
  65020. for (var j = 0; j < count; j++) {
  65021. scanLineArray[index++] = uint8array[dataIndex++];
  65022. }
  65023. }
  65024. }
  65025. }
  65026. }
  65027. // now convert data from buffer into floats
  65028. for (i = 0; i < scanline_width; i++) {
  65029. a = scanLineArray[i];
  65030. b = scanLineArray[i + scanline_width];
  65031. c = scanLineArray[i + 2 * scanline_width];
  65032. d = scanLineArray[i + 3 * scanline_width];
  65033. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  65034. }
  65035. num_scanlines--;
  65036. }
  65037. return resultArray;
  65038. };
  65039. return HDRTools;
  65040. }());
  65041. Internals.HDRTools = HDRTools;
  65042. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  65043. })(BABYLON || (BABYLON = {}));
  65044. //# sourceMappingURL=babylon.hdr.js.map
  65045. var BABYLON;
  65046. (function (BABYLON) {
  65047. /**
  65048. * This represents a texture coming from an HDR input.
  65049. *
  65050. * The only supported format is currently panorama picture stored in RGBE format.
  65051. * Example of such files can be found on HDRLib: http://hdrlib.com/
  65052. */
  65053. var HDRCubeTexture = /** @class */ (function (_super) {
  65054. __extends(HDRCubeTexture, _super);
  65055. /**
  65056. * Instantiates an HDRTexture from the following parameters.
  65057. *
  65058. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  65059. * @param scene The scene the texture will be used in
  65060. * @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.
  65061. * @param noMipmap Forces to not generate the mipmap if true
  65062. * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
  65063. * @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)
  65064. * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  65065. */
  65066. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  65067. if (noMipmap === void 0) { noMipmap = false; }
  65068. if (generateHarmonics === void 0) { generateHarmonics = true; }
  65069. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  65070. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  65071. if (onLoad === void 0) { onLoad = null; }
  65072. if (onError === void 0) { onError = null; }
  65073. var _this = _super.call(this, scene) || this;
  65074. _this._useInGammaSpace = false;
  65075. _this._generateHarmonics = true;
  65076. _this._isBABYLONPreprocessed = false;
  65077. _this._onLoad = null;
  65078. _this._onError = null;
  65079. /**
  65080. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  65081. */
  65082. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  65083. /**
  65084. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  65085. * This is usefull at run time to apply the good shader.
  65086. */
  65087. _this.isPMREM = false;
  65088. _this._isBlocking = true;
  65089. if (!url) {
  65090. return _this;
  65091. }
  65092. _this.name = url;
  65093. _this.url = url;
  65094. _this.hasAlpha = false;
  65095. _this.isCube = true;
  65096. _this._textureMatrix = BABYLON.Matrix.Identity();
  65097. _this._onLoad = onLoad;
  65098. _this._onError = onError;
  65099. _this.gammaSpace = false;
  65100. var caps = scene.getEngine().getCaps();
  65101. if (size) {
  65102. _this._isBABYLONPreprocessed = false;
  65103. _this._noMipmap = noMipmap;
  65104. _this._size = size;
  65105. _this._useInGammaSpace = useInGammaSpace;
  65106. _this._usePMREMGenerator = usePMREMGenerator &&
  65107. caps.textureLOD &&
  65108. caps.textureFloat &&
  65109. !_this._useInGammaSpace;
  65110. }
  65111. else {
  65112. _this._isBABYLONPreprocessed = true;
  65113. _this._noMipmap = false;
  65114. _this._useInGammaSpace = false;
  65115. _this._usePMREMGenerator = caps.textureLOD && caps.textureFloat &&
  65116. !_this._useInGammaSpace;
  65117. }
  65118. _this.isPMREM = _this._usePMREMGenerator;
  65119. _this._texture = _this._getFromCache(url, _this._noMipmap);
  65120. if (!_this._texture) {
  65121. if (!scene.useDelayedTextureLoading) {
  65122. _this.loadTexture();
  65123. }
  65124. else {
  65125. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  65126. }
  65127. }
  65128. return _this;
  65129. }
  65130. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  65131. /**
  65132. * Gets wether or not the texture is blocking during loading.
  65133. */
  65134. get: function () {
  65135. return this._isBlocking;
  65136. },
  65137. /**
  65138. * Sets wether or not the texture is blocking during loading.
  65139. */
  65140. set: function (value) {
  65141. this._isBlocking = value;
  65142. },
  65143. enumerable: true,
  65144. configurable: true
  65145. });
  65146. /**
  65147. * Occurs when the file is a preprocessed .babylon.hdr file.
  65148. */
  65149. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  65150. var _this = this;
  65151. var mipLevels = 0;
  65152. var floatArrayView = null;
  65153. var scene = this.getScene();
  65154. var mipmapGenerator = (!this._useInGammaSpace && scene && scene.getEngine().getCaps().textureFloat) ? function (data) {
  65155. var mips = new Array();
  65156. if (!floatArrayView) {
  65157. return mips;
  65158. }
  65159. var startIndex = 30;
  65160. for (var level = 0; level < mipLevels; level++) {
  65161. mips.push([]);
  65162. // Fill each pixel of the mip level.
  65163. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  65164. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  65165. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  65166. mips[level].push(faceData);
  65167. startIndex += faceSize;
  65168. }
  65169. }
  65170. return mips;
  65171. } : null;
  65172. var callback = function (buffer) {
  65173. var scene = _this.getScene();
  65174. if (!scene) {
  65175. return null;
  65176. }
  65177. // Create Native Array Views
  65178. var intArrayView = new Int32Array(buffer);
  65179. floatArrayView = new Float32Array(buffer);
  65180. // Fill header.
  65181. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  65182. _this._size = intArrayView[1]; // CubeMap max mip face size.
  65183. // Update Texture Information.
  65184. if (!_this._texture) {
  65185. return null;
  65186. }
  65187. _this._texture.updateSize(_this._size, _this._size);
  65188. // Fill polynomial information.
  65189. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  65190. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  65191. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  65192. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  65193. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  65194. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  65195. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  65196. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  65197. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  65198. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  65199. _this.sphericalPolynomial = sphericalPolynomial;
  65200. // Fill pixel data.
  65201. mipLevels = intArrayView[29]; // Number of mip levels.
  65202. var startIndex = 30;
  65203. var data = [];
  65204. var faceSize = Math.pow(_this._size, 2) * 3;
  65205. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  65206. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  65207. startIndex += faceSize;
  65208. }
  65209. var results = [];
  65210. var byteArray = null;
  65211. // Push each faces.
  65212. for (var k = 0; k < 6; k++) {
  65213. var dataFace = null;
  65214. // To be deprecated.
  65215. if (version === 1) {
  65216. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  65217. dataFace = data[j];
  65218. }
  65219. // If special cases.
  65220. if (!mipmapGenerator && dataFace) {
  65221. if (!scene.getEngine().getCaps().textureFloat) {
  65222. // 3 channels of 1 bytes per pixel in bytes.
  65223. var byteBuffer = new ArrayBuffer(faceSize);
  65224. byteArray = new Uint8Array(byteBuffer);
  65225. }
  65226. for (var i = 0; i < _this._size * _this._size; i++) {
  65227. // Put in gamma space if requested.
  65228. if (_this._useInGammaSpace) {
  65229. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  65230. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  65231. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  65232. }
  65233. // Convert to int texture for fallback.
  65234. if (byteArray) {
  65235. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  65236. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  65237. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  65238. // May use luminance instead if the result is not accurate.
  65239. var max = Math.max(Math.max(r, g), b);
  65240. if (max > 255) {
  65241. var scale = 255 / max;
  65242. r *= scale;
  65243. g *= scale;
  65244. b *= scale;
  65245. }
  65246. byteArray[(i * 3) + 0] = r;
  65247. byteArray[(i * 3) + 1] = g;
  65248. byteArray[(i * 3) + 2] = b;
  65249. }
  65250. }
  65251. }
  65252. // Fill the array accordingly.
  65253. if (byteArray) {
  65254. results.push(byteArray);
  65255. }
  65256. else {
  65257. results.push(dataFace);
  65258. }
  65259. }
  65260. return results;
  65261. };
  65262. if (scene) {
  65263. 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);
  65264. }
  65265. };
  65266. /**
  65267. * Occurs when the file is raw .hdr file.
  65268. */
  65269. HDRCubeTexture.prototype.loadHDRTexture = function () {
  65270. var _this = this;
  65271. var callback = function (buffer) {
  65272. var scene = _this.getScene();
  65273. if (!scene) {
  65274. return null;
  65275. }
  65276. // Extract the raw linear data.
  65277. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  65278. // Generate harmonics if needed.
  65279. if (_this._generateHarmonics) {
  65280. var sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  65281. _this.sphericalPolynomial = sphericalPolynomial;
  65282. }
  65283. var results = [];
  65284. var byteArray = null;
  65285. // Push each faces.
  65286. for (var j = 0; j < 6; j++) {
  65287. // Create uintarray fallback.
  65288. if (!scene.getEngine().getCaps().textureFloat) {
  65289. // 3 channels of 1 bytes per pixel in bytes.
  65290. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  65291. byteArray = new Uint8Array(byteBuffer);
  65292. }
  65293. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  65294. // If special cases.
  65295. if (_this._useInGammaSpace || byteArray) {
  65296. for (var i = 0; i < _this._size * _this._size; i++) {
  65297. // Put in gamma space if requested.
  65298. if (_this._useInGammaSpace) {
  65299. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  65300. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  65301. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  65302. }
  65303. // Convert to int texture for fallback.
  65304. if (byteArray) {
  65305. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  65306. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  65307. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  65308. // May use luminance instead if the result is not accurate.
  65309. var max = Math.max(Math.max(r, g), b);
  65310. if (max > 255) {
  65311. var scale = 255 / max;
  65312. r *= scale;
  65313. g *= scale;
  65314. b *= scale;
  65315. }
  65316. byteArray[(i * 3) + 0] = r;
  65317. byteArray[(i * 3) + 1] = g;
  65318. byteArray[(i * 3) + 2] = b;
  65319. }
  65320. }
  65321. }
  65322. if (byteArray) {
  65323. results.push(byteArray);
  65324. }
  65325. else {
  65326. results.push(dataFace);
  65327. }
  65328. }
  65329. return results;
  65330. };
  65331. var mipmapGenerator = null;
  65332. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  65333. // if (!this._noMipmap &&
  65334. // this._usePMREMGenerator) {
  65335. // mipmapGenerator = (data: ArrayBufferView[]) => {
  65336. // // Custom setup of the generator matching with the PBR shader values.
  65337. // var generator = new BABYLON.Internals.PMREMGenerator(data,
  65338. // this._size,
  65339. // this._size,
  65340. // 0,
  65341. // 3,
  65342. // this.getScene().getEngine().getCaps().textureFloat,
  65343. // 2048,
  65344. // 0.25,
  65345. // false,
  65346. // true);
  65347. // return generator.filterCubeMap();
  65348. // };
  65349. // }
  65350. var scene = this.getScene();
  65351. if (scene) {
  65352. 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);
  65353. }
  65354. };
  65355. /**
  65356. * Starts the loading process of the texture.
  65357. */
  65358. HDRCubeTexture.prototype.loadTexture = function () {
  65359. if (this._isBABYLONPreprocessed) {
  65360. this.loadBabylonTexture();
  65361. }
  65362. else {
  65363. this.loadHDRTexture();
  65364. }
  65365. };
  65366. HDRCubeTexture.prototype.clone = function () {
  65367. var scene = this.getScene();
  65368. if (!scene) {
  65369. return this;
  65370. }
  65371. var size = (this._isBABYLONPreprocessed ? null : this._size);
  65372. var newTexture = new HDRCubeTexture(this.url, scene, size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  65373. // Base texture
  65374. newTexture.level = this.level;
  65375. newTexture.wrapU = this.wrapU;
  65376. newTexture.wrapV = this.wrapV;
  65377. newTexture.coordinatesIndex = this.coordinatesIndex;
  65378. newTexture.coordinatesMode = this.coordinatesMode;
  65379. return newTexture;
  65380. };
  65381. // Methods
  65382. HDRCubeTexture.prototype.delayLoad = function () {
  65383. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  65384. return;
  65385. }
  65386. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  65387. this._texture = this._getFromCache(this.url, this._noMipmap);
  65388. if (!this._texture) {
  65389. this.loadTexture();
  65390. }
  65391. };
  65392. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  65393. return this._textureMatrix;
  65394. };
  65395. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  65396. this._textureMatrix = value;
  65397. };
  65398. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  65399. var texture = null;
  65400. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  65401. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  65402. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  65403. texture.name = parsedTexture.name;
  65404. texture.hasAlpha = parsedTexture.hasAlpha;
  65405. texture.level = parsedTexture.level;
  65406. texture.coordinatesMode = parsedTexture.coordinatesMode;
  65407. texture.isBlocking = parsedTexture.isBlocking;
  65408. }
  65409. return texture;
  65410. };
  65411. HDRCubeTexture.prototype.serialize = function () {
  65412. if (!this.name) {
  65413. return null;
  65414. }
  65415. var serializationObject = {};
  65416. serializationObject.name = this.name;
  65417. serializationObject.hasAlpha = this.hasAlpha;
  65418. serializationObject.isCube = true;
  65419. serializationObject.level = this.level;
  65420. serializationObject.size = this._size;
  65421. serializationObject.coordinatesMode = this.coordinatesMode;
  65422. serializationObject.useInGammaSpace = this._useInGammaSpace;
  65423. serializationObject.generateHarmonics = this._generateHarmonics;
  65424. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  65425. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  65426. serializationObject.customType = "BABYLON.HDRCubeTexture";
  65427. serializationObject.noMipmap = this._noMipmap;
  65428. serializationObject.isBlocking = this._isBlocking;
  65429. return serializationObject;
  65430. };
  65431. /**
  65432. * Saves as a file the data contained in the texture in a binary format.
  65433. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  65434. * as the spherical used in the lighting.
  65435. * @param url The HDR file url.
  65436. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  65437. * @param onError Method called if any error happens during download.
  65438. * @return The packed binary data.
  65439. */
  65440. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  65441. if (onError === void 0) { onError = null; }
  65442. var callback = function (buffer) {
  65443. var data = new Blob([buffer], { type: 'application/octet-stream' });
  65444. // Returns a URL you can use as a href.
  65445. var objUrl = window.URL.createObjectURL(data);
  65446. // Simulates a link to it and click to dowload.
  65447. var a = document.createElement("a");
  65448. document.body.appendChild(a);
  65449. a.style.display = "none";
  65450. a.href = objUrl;
  65451. a.download = "envmap.babylon.hdr";
  65452. a.click();
  65453. };
  65454. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  65455. };
  65456. /**
  65457. * Serializes the data contained in the texture in a binary format.
  65458. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  65459. * as the spherical used in the lighting.
  65460. * @param url The HDR file url.
  65461. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  65462. * @param onError Method called if any error happens during download.
  65463. * @return The packed binary data.
  65464. */
  65465. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  65466. if (onError === void 0) { onError = null; }
  65467. // Needs the url tho create the texture.
  65468. if (!url) {
  65469. return;
  65470. }
  65471. // Check Power of two size.
  65472. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  65473. return;
  65474. }
  65475. // Coming Back in 3.x.
  65476. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.2.");
  65477. };
  65478. HDRCubeTexture._facesMapping = [
  65479. "right",
  65480. "left",
  65481. "up",
  65482. "down",
  65483. "front",
  65484. "back"
  65485. ];
  65486. return HDRCubeTexture;
  65487. }(BABYLON.BaseTexture));
  65488. BABYLON.HDRCubeTexture = HDRCubeTexture;
  65489. })(BABYLON || (BABYLON = {}));
  65490. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  65491. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  65492. // Huge respect for a such great lib.
  65493. // Earcut license:
  65494. // Copyright (c) 2016, Mapbox
  65495. //
  65496. // Permission to use, copy, modify, and/or distribute this software for any purpose
  65497. // with or without fee is hereby granted, provided that the above copyright notice
  65498. // and this permission notice appear in all copies.
  65499. //
  65500. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  65501. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  65502. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  65503. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  65504. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  65505. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  65506. // THIS SOFTWARE.
  65507. var Earcut;
  65508. (function (Earcut) {
  65509. /**
  65510. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  65511. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  65512. * @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).
  65513. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  65514. */
  65515. function earcut(data, holeIndices, dim) {
  65516. dim = dim || 2;
  65517. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = new Array();
  65518. if (!outerNode)
  65519. return triangles;
  65520. var minX = 0, minY = 0, maxX, maxY, x, y, size = 0;
  65521. if (hasHoles)
  65522. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  65523. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  65524. if (data.length > 80 * dim) {
  65525. minX = maxX = data[0];
  65526. minY = maxY = data[1];
  65527. for (var i = dim; i < outerLen; i += dim) {
  65528. x = data[i];
  65529. y = data[i + 1];
  65530. if (x < minX)
  65531. minX = x;
  65532. if (y < minY)
  65533. minY = y;
  65534. if (x > maxX)
  65535. maxX = x;
  65536. if (y > maxY)
  65537. maxY = y;
  65538. }
  65539. // minX, minY and size are later used to transform coords into integers for z-order calculation
  65540. size = Math.max(maxX - minX, maxY - minY);
  65541. }
  65542. earcutLinked(outerNode, triangles, dim, minX, minY, size, 0);
  65543. return triangles;
  65544. }
  65545. Earcut.earcut = earcut;
  65546. var Node = /** @class */ (function () {
  65547. function Node(i, x, y) {
  65548. this.i = i;
  65549. this.x = x;
  65550. this.y = y;
  65551. this.prev = null;
  65552. this.next = null;
  65553. this.z = null;
  65554. this.prevZ = null;
  65555. this.nextZ = null;
  65556. this.steiner = false;
  65557. }
  65558. return Node;
  65559. }());
  65560. // create a circular doubly linked list from polygon points in the specified winding order
  65561. function linkedList(data, start, end, dim, clockwise) {
  65562. var i, last = null;
  65563. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  65564. for (i = start; i < end; i += dim)
  65565. last = insertNode(i, data[i], data[i + 1], last);
  65566. }
  65567. else {
  65568. for (i = end - dim; i >= start; i -= dim)
  65569. last = insertNode(i, data[i], data[i + 1], last);
  65570. }
  65571. if (last && equals(last, last.next)) {
  65572. removeNode(last);
  65573. last = last.next;
  65574. }
  65575. return last;
  65576. }
  65577. // eliminate colinear or duplicate points
  65578. function filterPoints(start, end) {
  65579. if (!start)
  65580. return start;
  65581. if (!end)
  65582. end = start;
  65583. var p = start, again;
  65584. do {
  65585. again = false;
  65586. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  65587. removeNode(p);
  65588. p = end = p.prev;
  65589. if (p === p.next)
  65590. return undefined;
  65591. again = true;
  65592. }
  65593. else {
  65594. p = p.next;
  65595. }
  65596. } while (again || p !== end);
  65597. return end;
  65598. }
  65599. // main ear slicing loop which triangulates a polygon (given as a linked list)
  65600. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  65601. if (!ear)
  65602. return;
  65603. // interlink polygon nodes in z-order
  65604. if (!pass && size)
  65605. indexCurve(ear, minX, minY, size);
  65606. var stop = ear, prev, next;
  65607. // iterate through ears, slicing them one by one
  65608. while (ear.prev !== ear.next) {
  65609. prev = ear.prev;
  65610. next = ear.next;
  65611. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  65612. // cut off the triangle
  65613. triangles.push(prev.i / dim);
  65614. triangles.push(ear.i / dim);
  65615. triangles.push(next.i / dim);
  65616. removeNode(ear);
  65617. // skipping the next vertice leads to less sliver triangles
  65618. ear = next.next;
  65619. stop = next.next;
  65620. continue;
  65621. }
  65622. ear = next;
  65623. // if we looped through the whole remaining polygon and can't find any more ears
  65624. if (ear === stop) {
  65625. // try filtering points and slicing again
  65626. if (!pass) {
  65627. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  65628. // if this didn't work, try curing all small self-intersections locally
  65629. }
  65630. else if (pass === 1) {
  65631. ear = cureLocalIntersections(ear, triangles, dim);
  65632. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  65633. // as a last resort, try splitting the remaining polygon into two
  65634. }
  65635. else if (pass === 2) {
  65636. splitEarcut(ear, triangles, dim, minX, minY, size);
  65637. }
  65638. break;
  65639. }
  65640. }
  65641. }
  65642. // check whether a polygon node forms a valid ear with adjacent nodes
  65643. function isEar(ear) {
  65644. var a = ear.prev, b = ear, c = ear.next;
  65645. if (area(a, b, c) >= 0)
  65646. return false; // reflex, can't be an ear
  65647. // now make sure we don't have other points inside the potential ear
  65648. var p = ear.next.next;
  65649. while (p !== ear.prev) {
  65650. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  65651. area(p.prev, p, p.next) >= 0)
  65652. return false;
  65653. p = p.next;
  65654. }
  65655. return true;
  65656. }
  65657. function isEarHashed(ear, minX, minY, size) {
  65658. var a = ear.prev, b = ear, c = ear.next;
  65659. if (area(a, b, c) >= 0)
  65660. return false; // reflex, can't be an ear
  65661. // triangle bbox; min & max are calculated like this for speed
  65662. 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);
  65663. // z-order range for the current triangle bbox;
  65664. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  65665. // first look for points inside the triangle in increasing z-order
  65666. var p = ear.nextZ;
  65667. while (p && p.z <= maxZ) {
  65668. if (p !== ear.prev &&
  65669. p !== ear.next &&
  65670. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  65671. area(p.prev, p, p.next) >= 0)
  65672. return false;
  65673. p = p.nextZ;
  65674. }
  65675. // then look for points in decreasing z-order
  65676. p = ear.prevZ;
  65677. while (p && p.z >= minZ) {
  65678. if (p !== ear.prev &&
  65679. p !== ear.next &&
  65680. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  65681. area(p.prev, p, p.next) >= 0)
  65682. return false;
  65683. p = p.prevZ;
  65684. }
  65685. return true;
  65686. }
  65687. // go through all polygon nodes and cure small local self-intersections
  65688. function cureLocalIntersections(start, triangles, dim) {
  65689. var p = start;
  65690. do {
  65691. var a = p.prev, b = p.next.next;
  65692. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  65693. triangles.push(a.i / dim);
  65694. triangles.push(p.i / dim);
  65695. triangles.push(b.i / dim);
  65696. // remove two nodes involved
  65697. removeNode(p);
  65698. removeNode(p.next);
  65699. p = start = b;
  65700. }
  65701. p = p.next;
  65702. } while (p !== start);
  65703. return p;
  65704. }
  65705. // try splitting polygon into two and triangulate them independently
  65706. function splitEarcut(start, triangles, dim, minX, minY, size) {
  65707. // look for a valid diagonal that divides the polygon into two
  65708. var a = start;
  65709. do {
  65710. var b = a.next.next;
  65711. while (b !== a.prev) {
  65712. if (a.i !== b.i && isValidDiagonal(a, b)) {
  65713. // split the polygon in two by the diagonal
  65714. var c = splitPolygon(a, b);
  65715. // filter colinear points around the cuts
  65716. a = filterPoints(a, a.next);
  65717. c = filterPoints(c, c.next);
  65718. // run earcut on each half
  65719. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  65720. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  65721. return;
  65722. }
  65723. b = b.next;
  65724. }
  65725. a = a.next;
  65726. } while (a !== start);
  65727. }
  65728. // link every hole into the outer loop, producing a single-ring polygon without holes
  65729. function eliminateHoles(data, holeIndices, outerNode, dim) {
  65730. var queue = [], i, len, start, end, list;
  65731. for (i = 0, len = holeIndices.length; i < len; i++) {
  65732. start = holeIndices[i] * dim;
  65733. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  65734. list = linkedList(data, start, end, dim, false);
  65735. if (list === list.next)
  65736. list.steiner = true;
  65737. queue.push(getLeftmost(list));
  65738. }
  65739. queue.sort(compareX);
  65740. // process holes from left to right
  65741. for (i = 0; i < queue.length; i++) {
  65742. eliminateHole(queue[i], outerNode);
  65743. outerNode = filterPoints(outerNode, outerNode.next);
  65744. }
  65745. return outerNode;
  65746. }
  65747. function compareX(a, b) {
  65748. return a.x - b.x;
  65749. }
  65750. // find a bridge between vertices that connects hole with an outer ring and and link it
  65751. function eliminateHole(hole, outerNode) {
  65752. outerNode = findHoleBridge(hole, outerNode);
  65753. if (outerNode) {
  65754. var b = splitPolygon(outerNode, hole);
  65755. filterPoints(b, b.next);
  65756. }
  65757. }
  65758. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  65759. function findHoleBridge(hole, outerNode) {
  65760. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  65761. // find a segment intersected by a ray from the hole's leftmost point to the left;
  65762. // segment's endpoint with lesser x will be potential connection point
  65763. do {
  65764. if (hy <= p.y && hy >= p.next.y) {
  65765. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  65766. if (x <= hx && x > qx) {
  65767. qx = x;
  65768. if (x === hx) {
  65769. if (hy === p.y)
  65770. return p;
  65771. if (hy === p.next.y)
  65772. return p.next;
  65773. }
  65774. m = p.x < p.next.x ? p : p.next;
  65775. }
  65776. }
  65777. p = p.next;
  65778. } while (p !== outerNode);
  65779. if (!m)
  65780. return null;
  65781. if (hx === qx)
  65782. return m.prev; // hole touches outer segment; pick lower endpoint
  65783. // look for points inside the triangle of hole point, segment intersection and endpoint;
  65784. // if there are no points found, we have a valid connection;
  65785. // otherwise choose the point of the minimum angle with the ray as connection point
  65786. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  65787. p = m.next;
  65788. while (p !== stop) {
  65789. if (hx >= p.x &&
  65790. p.x >= mx &&
  65791. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  65792. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  65793. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  65794. m = p;
  65795. tanMin = tan;
  65796. }
  65797. }
  65798. p = p.next;
  65799. }
  65800. return m;
  65801. }
  65802. // interlink polygon nodes in z-order
  65803. function indexCurve(start, minX, minY, size) {
  65804. var p = start;
  65805. do {
  65806. if (p.z === null)
  65807. p.z = zOrder(p.x, p.y, minX, minY, size);
  65808. p.prevZ = p.prev;
  65809. p.nextZ = p.next;
  65810. p = p.next;
  65811. } while (p !== start);
  65812. p.prevZ.nextZ = null;
  65813. p.prevZ = null;
  65814. sortLinked(p);
  65815. }
  65816. // Simon Tatham's linked list merge sort algorithm
  65817. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  65818. function sortLinked(list) {
  65819. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  65820. do {
  65821. p = list;
  65822. list = null;
  65823. tail = null;
  65824. numMerges = 0;
  65825. while (p) {
  65826. numMerges++;
  65827. q = p;
  65828. pSize = 0;
  65829. for (i = 0; i < inSize; i++) {
  65830. pSize++;
  65831. q = q.nextZ;
  65832. if (!q)
  65833. break;
  65834. }
  65835. qSize = inSize;
  65836. while (pSize > 0 || (qSize > 0 && q)) {
  65837. if (pSize === 0) {
  65838. e = q;
  65839. q = q.nextZ;
  65840. qSize--;
  65841. }
  65842. else if (qSize === 0 || !q) {
  65843. e = p;
  65844. p = p.nextZ;
  65845. pSize--;
  65846. }
  65847. else if (p.z <= q.z) {
  65848. e = p;
  65849. p = p.nextZ;
  65850. pSize--;
  65851. }
  65852. else {
  65853. e = q;
  65854. q = q.nextZ;
  65855. qSize--;
  65856. }
  65857. if (tail)
  65858. tail.nextZ = e;
  65859. else
  65860. list = e;
  65861. e.prevZ = tail;
  65862. tail = e;
  65863. }
  65864. p = q;
  65865. }
  65866. tail.nextZ = null;
  65867. inSize *= 2;
  65868. } while (numMerges > 1);
  65869. return list;
  65870. }
  65871. // z-order of a point given coords and size of the data bounding box
  65872. function zOrder(x, y, minX, minY, size) {
  65873. // coords are transformed into non-negative 15-bit integer range
  65874. x = 32767 * (x - minX) / size;
  65875. y = 32767 * (y - minY) / size;
  65876. x = (x | (x << 8)) & 0x00FF00FF;
  65877. x = (x | (x << 4)) & 0x0F0F0F0F;
  65878. x = (x | (x << 2)) & 0x33333333;
  65879. x = (x | (x << 1)) & 0x55555555;
  65880. y = (y | (y << 8)) & 0x00FF00FF;
  65881. y = (y | (y << 4)) & 0x0F0F0F0F;
  65882. y = (y | (y << 2)) & 0x33333333;
  65883. y = (y | (y << 1)) & 0x55555555;
  65884. return x | (y << 1);
  65885. }
  65886. // find the leftmost node of a polygon ring
  65887. function getLeftmost(start) {
  65888. var p = start, leftmost = start;
  65889. do {
  65890. if (p.x < leftmost.x)
  65891. leftmost = p;
  65892. p = p.next;
  65893. } while (p !== start);
  65894. return leftmost;
  65895. }
  65896. // check if a point lies within a convex triangle
  65897. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  65898. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  65899. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  65900. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  65901. }
  65902. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  65903. function isValidDiagonal(a, b) {
  65904. return a.next.i !== b.i &&
  65905. a.prev.i !== b.i &&
  65906. !intersectsPolygon(a, b) &&
  65907. locallyInside(a, b) &&
  65908. locallyInside(b, a) &&
  65909. middleInside(a, b);
  65910. }
  65911. // signed area of a triangle
  65912. function area(p, q, r) {
  65913. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  65914. }
  65915. // check if two points are equal
  65916. function equals(p1, p2) {
  65917. return p1.x === p2.x && p1.y === p2.y;
  65918. }
  65919. // check if two segments intersect
  65920. function intersects(p1, q1, p2, q2) {
  65921. if ((equals(p1, q1) && equals(p2, q2)) ||
  65922. (equals(p1, q2) && equals(p2, q1)))
  65923. return true;
  65924. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  65925. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  65926. }
  65927. // check if a polygon diagonal intersects any polygon segments
  65928. function intersectsPolygon(a, b) {
  65929. var p = a;
  65930. do {
  65931. if (p.i !== a.i &&
  65932. p.next.i !== a.i &&
  65933. p.i !== b.i &&
  65934. p.next.i !== b.i &&
  65935. intersects(p, p.next, a, b))
  65936. return true;
  65937. p = p.next;
  65938. } while (p !== a);
  65939. return false;
  65940. }
  65941. // check if a polygon diagonal is locally inside the polygon
  65942. function locallyInside(a, b) {
  65943. return area(a.prev, a, a.next) < 0
  65944. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  65945. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  65946. }
  65947. // check if the middle point of a polygon diagonal is inside the polygon
  65948. function middleInside(a, b) {
  65949. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  65950. do {
  65951. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  65952. inside = !inside;
  65953. p = p.next;
  65954. } while (p !== a);
  65955. return inside;
  65956. }
  65957. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  65958. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  65959. function splitPolygon(a, b) {
  65960. 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;
  65961. a.next = b;
  65962. b.prev = a;
  65963. a2.next = an;
  65964. an.prev = a2;
  65965. b2.next = a2;
  65966. a2.prev = b2;
  65967. bp.next = b2;
  65968. b2.prev = bp;
  65969. return b2;
  65970. }
  65971. // create a node and optionally link it with previous one (in a circular doubly linked list)
  65972. function insertNode(i, x, y, last) {
  65973. var p = new Node(i, x, y);
  65974. if (!last) {
  65975. p.prev = p;
  65976. p.next = p;
  65977. }
  65978. else {
  65979. p.next = last.next;
  65980. p.prev = last;
  65981. last.next.prev = p;
  65982. last.next = p;
  65983. }
  65984. return p;
  65985. }
  65986. function removeNode(p) {
  65987. p.next.prev = p.prev;
  65988. p.prev.next = p.next;
  65989. if (p.prevZ)
  65990. p.prevZ.nextZ = p.nextZ;
  65991. if (p.nextZ)
  65992. p.nextZ.prevZ = p.prevZ;
  65993. }
  65994. /**
  65995. * return a percentage difference between the polygon area and its triangulation area;
  65996. * used to verify correctness of triangulation
  65997. */
  65998. function deviation(data, holeIndices, dim, triangles) {
  65999. var hasHoles = holeIndices && holeIndices.length;
  66000. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  66001. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  66002. if (hasHoles) {
  66003. for (var i = 0, len = holeIndices.length; i < len; i++) {
  66004. var start = holeIndices[i] * dim;
  66005. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  66006. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  66007. }
  66008. }
  66009. var trianglesArea = 0;
  66010. for (i = 0; i < triangles.length; i += 3) {
  66011. var a = triangles[i] * dim;
  66012. var b = triangles[i + 1] * dim;
  66013. var c = triangles[i + 2] * dim;
  66014. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  66015. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  66016. }
  66017. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  66018. }
  66019. Earcut.deviation = deviation;
  66020. ;
  66021. function signedArea(data, start, end, dim) {
  66022. var sum = 0;
  66023. for (var i = start, j = end - dim; i < end; i += dim) {
  66024. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  66025. j = i;
  66026. }
  66027. return sum;
  66028. }
  66029. /**
  66030. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  66031. */
  66032. function flatten(data) {
  66033. var dim = data[0][0].length, result = { vertices: new Array(), holes: new Array(), dimensions: dim }, holeIndex = 0;
  66034. for (var i = 0; i < data.length; i++) {
  66035. for (var j = 0; j < data[i].length; j++) {
  66036. for (var d = 0; d < dim; d++)
  66037. result.vertices.push(data[i][j][d]);
  66038. }
  66039. if (i > 0) {
  66040. holeIndex += data[i - 1].length;
  66041. result.holes.push(holeIndex);
  66042. }
  66043. }
  66044. return result;
  66045. }
  66046. Earcut.flatten = flatten;
  66047. ;
  66048. })(Earcut || (Earcut = {}));
  66049. //# sourceMappingURL=babylon.earcut.js.map
  66050. var BABYLON;
  66051. (function (BABYLON) {
  66052. var IndexedVector2 = /** @class */ (function (_super) {
  66053. __extends(IndexedVector2, _super);
  66054. function IndexedVector2(original, index) {
  66055. var _this = _super.call(this, original.x, original.y) || this;
  66056. _this.index = index;
  66057. return _this;
  66058. }
  66059. return IndexedVector2;
  66060. }(BABYLON.Vector2));
  66061. var PolygonPoints = /** @class */ (function () {
  66062. function PolygonPoints() {
  66063. this.elements = new Array();
  66064. }
  66065. PolygonPoints.prototype.add = function (originalPoints) {
  66066. var _this = this;
  66067. var result = new Array();
  66068. originalPoints.forEach(function (point) {
  66069. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  66070. var newPoint = new IndexedVector2(point, _this.elements.length);
  66071. result.push(newPoint);
  66072. _this.elements.push(newPoint);
  66073. }
  66074. });
  66075. return result;
  66076. };
  66077. PolygonPoints.prototype.computeBounds = function () {
  66078. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  66079. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  66080. this.elements.forEach(function (point) {
  66081. // x
  66082. if (point.x < lmin.x) {
  66083. lmin.x = point.x;
  66084. }
  66085. else if (point.x > lmax.x) {
  66086. lmax.x = point.x;
  66087. }
  66088. // y
  66089. if (point.y < lmin.y) {
  66090. lmin.y = point.y;
  66091. }
  66092. else if (point.y > lmax.y) {
  66093. lmax.y = point.y;
  66094. }
  66095. });
  66096. return {
  66097. min: lmin,
  66098. max: lmax,
  66099. width: lmax.x - lmin.x,
  66100. height: lmax.y - lmin.y
  66101. };
  66102. };
  66103. return PolygonPoints;
  66104. }());
  66105. var Polygon = /** @class */ (function () {
  66106. function Polygon() {
  66107. }
  66108. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  66109. return [
  66110. new BABYLON.Vector2(xmin, ymin),
  66111. new BABYLON.Vector2(xmax, ymin),
  66112. new BABYLON.Vector2(xmax, ymax),
  66113. new BABYLON.Vector2(xmin, ymax)
  66114. ];
  66115. };
  66116. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  66117. if (cx === void 0) { cx = 0; }
  66118. if (cy === void 0) { cy = 0; }
  66119. if (numberOfSides === void 0) { numberOfSides = 32; }
  66120. var result = new Array();
  66121. var angle = 0;
  66122. var increment = (Math.PI * 2) / numberOfSides;
  66123. for (var i = 0; i < numberOfSides; i++) {
  66124. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  66125. angle -= increment;
  66126. }
  66127. return result;
  66128. };
  66129. Polygon.Parse = function (input) {
  66130. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  66131. var i, result = [];
  66132. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  66133. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  66134. }
  66135. return result;
  66136. };
  66137. Polygon.StartingAt = function (x, y) {
  66138. return BABYLON.Path2.StartingAt(x, y);
  66139. };
  66140. return Polygon;
  66141. }());
  66142. BABYLON.Polygon = Polygon;
  66143. var PolygonMeshBuilder = /** @class */ (function () {
  66144. function PolygonMeshBuilder(name, contours, scene) {
  66145. this._points = new PolygonPoints();
  66146. this._outlinepoints = new PolygonPoints();
  66147. this._holes = new Array();
  66148. this._epoints = new Array();
  66149. this._eholes = new Array();
  66150. this._name = name;
  66151. this._scene = scene;
  66152. var points;
  66153. if (contours instanceof BABYLON.Path2) {
  66154. points = contours.getPoints();
  66155. }
  66156. else {
  66157. points = contours;
  66158. }
  66159. this._addToepoint(points);
  66160. this._points.add(points);
  66161. this._outlinepoints.add(points);
  66162. }
  66163. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  66164. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  66165. var p = points_1[_i];
  66166. this._epoints.push(p.x, p.y);
  66167. }
  66168. };
  66169. PolygonMeshBuilder.prototype.addHole = function (hole) {
  66170. this._points.add(hole);
  66171. var holepoints = new PolygonPoints();
  66172. holepoints.add(hole);
  66173. this._holes.push(holepoints);
  66174. this._eholes.push(this._epoints.length / 2);
  66175. this._addToepoint(hole);
  66176. return this;
  66177. };
  66178. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  66179. var _this = this;
  66180. if (updatable === void 0) { updatable = false; }
  66181. if (depth === void 0) { depth = 0; }
  66182. var result = new BABYLON.Mesh(this._name, this._scene);
  66183. var normals = new Array();
  66184. var positions = new Array();
  66185. var uvs = new Array();
  66186. var bounds = this._points.computeBounds();
  66187. this._points.elements.forEach(function (p) {
  66188. normals.push(0, 1.0, 0);
  66189. positions.push(p.x, 0, p.y);
  66190. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  66191. });
  66192. var indices = new Array();
  66193. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  66194. for (var i = 0; i < res.length; i++) {
  66195. indices.push(res[i]);
  66196. }
  66197. if (depth > 0) {
  66198. var positionscount = (positions.length / 3); //get the current pointcount
  66199. this._points.elements.forEach(function (p) {
  66200. normals.push(0, -1.0, 0);
  66201. positions.push(p.x, -depth, p.y);
  66202. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  66203. });
  66204. var totalCount = indices.length;
  66205. for (var i = 0; i < totalCount; i += 3) {
  66206. var i0 = indices[i + 0];
  66207. var i1 = indices[i + 1];
  66208. var i2 = indices[i + 2];
  66209. indices.push(i2 + positionscount);
  66210. indices.push(i1 + positionscount);
  66211. indices.push(i0 + positionscount);
  66212. }
  66213. //Add the sides
  66214. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  66215. this._holes.forEach(function (hole) {
  66216. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  66217. });
  66218. }
  66219. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  66220. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  66221. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  66222. result.setIndices(indices);
  66223. return result;
  66224. };
  66225. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  66226. var StartIndex = positions.length / 3;
  66227. var ulength = 0;
  66228. for (var i = 0; i < points.elements.length; i++) {
  66229. var p = points.elements[i];
  66230. var p1;
  66231. if ((i + 1) > points.elements.length - 1) {
  66232. p1 = points.elements[0];
  66233. }
  66234. else {
  66235. p1 = points.elements[i + 1];
  66236. }
  66237. positions.push(p.x, 0, p.y);
  66238. positions.push(p.x, -depth, p.y);
  66239. positions.push(p1.x, 0, p1.y);
  66240. positions.push(p1.x, -depth, p1.y);
  66241. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  66242. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  66243. var v3 = v2.subtract(v1);
  66244. var v4 = new BABYLON.Vector3(0, 1, 0);
  66245. var vn = BABYLON.Vector3.Cross(v3, v4);
  66246. vn = vn.normalize();
  66247. uvs.push(ulength / bounds.width, 0);
  66248. uvs.push(ulength / bounds.width, 1);
  66249. ulength += v3.length();
  66250. uvs.push((ulength / bounds.width), 0);
  66251. uvs.push((ulength / bounds.width), 1);
  66252. if (!flip) {
  66253. normals.push(-vn.x, -vn.y, -vn.z);
  66254. normals.push(-vn.x, -vn.y, -vn.z);
  66255. normals.push(-vn.x, -vn.y, -vn.z);
  66256. normals.push(-vn.x, -vn.y, -vn.z);
  66257. indices.push(StartIndex);
  66258. indices.push(StartIndex + 1);
  66259. indices.push(StartIndex + 2);
  66260. indices.push(StartIndex + 1);
  66261. indices.push(StartIndex + 3);
  66262. indices.push(StartIndex + 2);
  66263. }
  66264. else {
  66265. normals.push(vn.x, vn.y, vn.z);
  66266. normals.push(vn.x, vn.y, vn.z);
  66267. normals.push(vn.x, vn.y, vn.z);
  66268. normals.push(vn.x, vn.y, vn.z);
  66269. indices.push(StartIndex);
  66270. indices.push(StartIndex + 2);
  66271. indices.push(StartIndex + 1);
  66272. indices.push(StartIndex + 1);
  66273. indices.push(StartIndex + 2);
  66274. indices.push(StartIndex + 3);
  66275. }
  66276. StartIndex += 4;
  66277. }
  66278. ;
  66279. };
  66280. return PolygonMeshBuilder;
  66281. }());
  66282. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  66283. })(BABYLON || (BABYLON = {}));
  66284. //# sourceMappingURL=babylon.polygonMesh.js.map
  66285. var BABYLON;
  66286. (function (BABYLON) {
  66287. // Unique ID when we import meshes from Babylon to CSG
  66288. var currentCSGMeshId = 0;
  66289. // # class Vertex
  66290. // Represents a vertex of a polygon. Use your own vertex class instead of this
  66291. // one to provide additional features like texture coordinates and vertex
  66292. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  66293. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  66294. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  66295. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  66296. // is not used anywhere else.
  66297. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  66298. var Vertex = /** @class */ (function () {
  66299. function Vertex(pos, normal, uv) {
  66300. this.pos = pos;
  66301. this.normal = normal;
  66302. this.uv = uv;
  66303. }
  66304. Vertex.prototype.clone = function () {
  66305. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  66306. };
  66307. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  66308. // orientation of a polygon is flipped.
  66309. Vertex.prototype.flip = function () {
  66310. this.normal = this.normal.scale(-1);
  66311. };
  66312. // Create a new vertex between this vertex and `other` by linearly
  66313. // interpolating all properties using a parameter of `t`. Subclasses should
  66314. // override this to interpolate additional properties.
  66315. Vertex.prototype.interpolate = function (other, t) {
  66316. 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));
  66317. };
  66318. return Vertex;
  66319. }());
  66320. // # class Plane
  66321. // Represents a plane in 3D space.
  66322. var Plane = /** @class */ (function () {
  66323. function Plane(normal, w) {
  66324. this.normal = normal;
  66325. this.w = w;
  66326. }
  66327. Plane.FromPoints = function (a, b, c) {
  66328. var v0 = c.subtract(a);
  66329. var v1 = b.subtract(a);
  66330. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  66331. return null;
  66332. }
  66333. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  66334. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  66335. };
  66336. Plane.prototype.clone = function () {
  66337. return new Plane(this.normal.clone(), this.w);
  66338. };
  66339. Plane.prototype.flip = function () {
  66340. this.normal.scaleInPlace(-1);
  66341. this.w = -this.w;
  66342. };
  66343. // Split `polygon` by this plane if needed, then put the polygon or polygon
  66344. // fragments in the appropriate lists. Coplanar polygons go into either
  66345. // `coplanarFront` or `coplanarBack` depending on their orientation with
  66346. // respect to this plane. Polygons in front or in back of this plane go into
  66347. // either `front` or `back`.
  66348. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  66349. var COPLANAR = 0;
  66350. var FRONT = 1;
  66351. var BACK = 2;
  66352. var SPANNING = 3;
  66353. // Classify each point as well as the entire polygon into one of the above
  66354. // four classes.
  66355. var polygonType = 0;
  66356. var types = [];
  66357. var i;
  66358. var t;
  66359. for (i = 0; i < polygon.vertices.length; i++) {
  66360. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  66361. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  66362. polygonType |= type;
  66363. types.push(type);
  66364. }
  66365. // Put the polygon in the correct list, splitting it when necessary.
  66366. switch (polygonType) {
  66367. case COPLANAR:
  66368. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  66369. break;
  66370. case FRONT:
  66371. front.push(polygon);
  66372. break;
  66373. case BACK:
  66374. back.push(polygon);
  66375. break;
  66376. case SPANNING:
  66377. var f = [], b = [];
  66378. for (i = 0; i < polygon.vertices.length; i++) {
  66379. var j = (i + 1) % polygon.vertices.length;
  66380. var ti = types[i], tj = types[j];
  66381. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  66382. if (ti !== BACK)
  66383. f.push(vi);
  66384. if (ti !== FRONT)
  66385. b.push(ti !== BACK ? vi.clone() : vi);
  66386. if ((ti | tj) === SPANNING) {
  66387. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  66388. var v = vi.interpolate(vj, t);
  66389. f.push(v);
  66390. b.push(v.clone());
  66391. }
  66392. }
  66393. var poly;
  66394. if (f.length >= 3) {
  66395. poly = new Polygon(f, polygon.shared);
  66396. if (poly.plane)
  66397. front.push(poly);
  66398. }
  66399. if (b.length >= 3) {
  66400. poly = new Polygon(b, polygon.shared);
  66401. if (poly.plane)
  66402. back.push(poly);
  66403. }
  66404. break;
  66405. }
  66406. };
  66407. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  66408. // point is on the plane.
  66409. Plane.EPSILON = 1e-5;
  66410. return Plane;
  66411. }());
  66412. // # class Polygon
  66413. // Represents a convex polygon. The vertices used to initialize a polygon must
  66414. // be coplanar and form a convex loop.
  66415. //
  66416. // Each convex polygon has a `shared` property, which is shared between all
  66417. // polygons that are clones of each other or were split from the same polygon.
  66418. // This can be used to define per-polygon properties (such as surface color).
  66419. var Polygon = /** @class */ (function () {
  66420. function Polygon(vertices, shared) {
  66421. this.vertices = vertices;
  66422. this.shared = shared;
  66423. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  66424. }
  66425. Polygon.prototype.clone = function () {
  66426. var vertices = this.vertices.map(function (v) { return v.clone(); });
  66427. return new Polygon(vertices, this.shared);
  66428. };
  66429. Polygon.prototype.flip = function () {
  66430. this.vertices.reverse().map(function (v) { v.flip(); });
  66431. this.plane.flip();
  66432. };
  66433. return Polygon;
  66434. }());
  66435. // # class Node
  66436. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  66437. // by picking a polygon to split along. That polygon (and all other coplanar
  66438. // polygons) are added directly to that node and the other polygons are added to
  66439. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  66440. // no distinction between internal and leaf nodes.
  66441. var Node = /** @class */ (function () {
  66442. function Node(polygons) {
  66443. this.plane = null;
  66444. this.front = null;
  66445. this.back = null;
  66446. this.polygons = new Array();
  66447. if (polygons) {
  66448. this.build(polygons);
  66449. }
  66450. }
  66451. Node.prototype.clone = function () {
  66452. var node = new Node();
  66453. node.plane = this.plane && this.plane.clone();
  66454. node.front = this.front && this.front.clone();
  66455. node.back = this.back && this.back.clone();
  66456. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  66457. return node;
  66458. };
  66459. // Convert solid space to empty space and empty space to solid space.
  66460. Node.prototype.invert = function () {
  66461. for (var i = 0; i < this.polygons.length; i++) {
  66462. this.polygons[i].flip();
  66463. }
  66464. if (this.plane) {
  66465. this.plane.flip();
  66466. }
  66467. if (this.front) {
  66468. this.front.invert();
  66469. }
  66470. if (this.back) {
  66471. this.back.invert();
  66472. }
  66473. var temp = this.front;
  66474. this.front = this.back;
  66475. this.back = temp;
  66476. };
  66477. // Recursively remove all polygons in `polygons` that are inside this BSP
  66478. // tree.
  66479. Node.prototype.clipPolygons = function (polygons) {
  66480. if (!this.plane)
  66481. return polygons.slice();
  66482. var front = new Array(), back = new Array();
  66483. for (var i = 0; i < polygons.length; i++) {
  66484. this.plane.splitPolygon(polygons[i], front, back, front, back);
  66485. }
  66486. if (this.front) {
  66487. front = this.front.clipPolygons(front);
  66488. }
  66489. if (this.back) {
  66490. back = this.back.clipPolygons(back);
  66491. }
  66492. else {
  66493. back = [];
  66494. }
  66495. return front.concat(back);
  66496. };
  66497. // Remove all polygons in this BSP tree that are inside the other BSP tree
  66498. // `bsp`.
  66499. Node.prototype.clipTo = function (bsp) {
  66500. this.polygons = bsp.clipPolygons(this.polygons);
  66501. if (this.front)
  66502. this.front.clipTo(bsp);
  66503. if (this.back)
  66504. this.back.clipTo(bsp);
  66505. };
  66506. // Return a list of all polygons in this BSP tree.
  66507. Node.prototype.allPolygons = function () {
  66508. var polygons = this.polygons.slice();
  66509. if (this.front)
  66510. polygons = polygons.concat(this.front.allPolygons());
  66511. if (this.back)
  66512. polygons = polygons.concat(this.back.allPolygons());
  66513. return polygons;
  66514. };
  66515. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  66516. // new polygons are filtered down to the bottom of the tree and become new
  66517. // nodes there. Each set of polygons is partitioned using the first polygon
  66518. // (no heuristic is used to pick a good split).
  66519. Node.prototype.build = function (polygons) {
  66520. if (!polygons.length)
  66521. return;
  66522. if (!this.plane)
  66523. this.plane = polygons[0].plane.clone();
  66524. var front = new Array(), back = new Array();
  66525. for (var i = 0; i < polygons.length; i++) {
  66526. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  66527. }
  66528. if (front.length) {
  66529. if (!this.front)
  66530. this.front = new Node();
  66531. this.front.build(front);
  66532. }
  66533. if (back.length) {
  66534. if (!this.back)
  66535. this.back = new Node();
  66536. this.back.build(back);
  66537. }
  66538. };
  66539. return Node;
  66540. }());
  66541. var CSG = /** @class */ (function () {
  66542. function CSG() {
  66543. this.polygons = new Array();
  66544. }
  66545. // Convert BABYLON.Mesh to BABYLON.CSG
  66546. CSG.FromMesh = function (mesh) {
  66547. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  66548. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  66549. if (mesh instanceof BABYLON.Mesh) {
  66550. mesh.computeWorldMatrix(true);
  66551. matrix = mesh.getWorldMatrix();
  66552. meshPosition = mesh.position.clone();
  66553. meshRotation = mesh.rotation.clone();
  66554. if (mesh.rotationQuaternion) {
  66555. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  66556. }
  66557. meshScaling = mesh.scaling.clone();
  66558. }
  66559. else {
  66560. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  66561. }
  66562. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  66563. var subMeshes = mesh.subMeshes;
  66564. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  66565. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  66566. vertices = [];
  66567. for (var j = 0; j < 3; j++) {
  66568. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  66569. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  66570. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  66571. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  66572. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  66573. vertex = new Vertex(position, normal, uv);
  66574. vertices.push(vertex);
  66575. }
  66576. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  66577. // To handle the case of degenerated triangle
  66578. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  66579. if (polygon.plane)
  66580. polygons.push(polygon);
  66581. }
  66582. }
  66583. var csg = CSG.FromPolygons(polygons);
  66584. csg.matrix = matrix;
  66585. csg.position = meshPosition;
  66586. csg.rotation = meshRotation;
  66587. csg.scaling = meshScaling;
  66588. csg.rotationQuaternion = meshRotationQuaternion;
  66589. currentCSGMeshId++;
  66590. return csg;
  66591. };
  66592. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  66593. CSG.FromPolygons = function (polygons) {
  66594. var csg = new CSG();
  66595. csg.polygons = polygons;
  66596. return csg;
  66597. };
  66598. CSG.prototype.clone = function () {
  66599. var csg = new CSG();
  66600. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  66601. csg.copyTransformAttributes(this);
  66602. return csg;
  66603. };
  66604. CSG.prototype.union = function (csg) {
  66605. var a = new Node(this.clone().polygons);
  66606. var b = new Node(csg.clone().polygons);
  66607. a.clipTo(b);
  66608. b.clipTo(a);
  66609. b.invert();
  66610. b.clipTo(a);
  66611. b.invert();
  66612. a.build(b.allPolygons());
  66613. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  66614. };
  66615. CSG.prototype.unionInPlace = function (csg) {
  66616. var a = new Node(this.polygons);
  66617. var b = new Node(csg.polygons);
  66618. a.clipTo(b);
  66619. b.clipTo(a);
  66620. b.invert();
  66621. b.clipTo(a);
  66622. b.invert();
  66623. a.build(b.allPolygons());
  66624. this.polygons = a.allPolygons();
  66625. };
  66626. CSG.prototype.subtract = function (csg) {
  66627. var a = new Node(this.clone().polygons);
  66628. var b = new Node(csg.clone().polygons);
  66629. a.invert();
  66630. a.clipTo(b);
  66631. b.clipTo(a);
  66632. b.invert();
  66633. b.clipTo(a);
  66634. b.invert();
  66635. a.build(b.allPolygons());
  66636. a.invert();
  66637. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  66638. };
  66639. CSG.prototype.subtractInPlace = function (csg) {
  66640. var a = new Node(this.polygons);
  66641. var b = new Node(csg.polygons);
  66642. a.invert();
  66643. a.clipTo(b);
  66644. b.clipTo(a);
  66645. b.invert();
  66646. b.clipTo(a);
  66647. b.invert();
  66648. a.build(b.allPolygons());
  66649. a.invert();
  66650. this.polygons = a.allPolygons();
  66651. };
  66652. CSG.prototype.intersect = function (csg) {
  66653. var a = new Node(this.clone().polygons);
  66654. var b = new Node(csg.clone().polygons);
  66655. a.invert();
  66656. b.clipTo(a);
  66657. b.invert();
  66658. a.clipTo(b);
  66659. b.clipTo(a);
  66660. a.build(b.allPolygons());
  66661. a.invert();
  66662. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  66663. };
  66664. CSG.prototype.intersectInPlace = function (csg) {
  66665. var a = new Node(this.polygons);
  66666. var b = new Node(csg.polygons);
  66667. a.invert();
  66668. b.clipTo(a);
  66669. b.invert();
  66670. a.clipTo(b);
  66671. b.clipTo(a);
  66672. a.build(b.allPolygons());
  66673. a.invert();
  66674. this.polygons = a.allPolygons();
  66675. };
  66676. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  66677. // not modified.
  66678. CSG.prototype.inverse = function () {
  66679. var csg = this.clone();
  66680. csg.inverseInPlace();
  66681. return csg;
  66682. };
  66683. CSG.prototype.inverseInPlace = function () {
  66684. this.polygons.map(function (p) { p.flip(); });
  66685. };
  66686. // This is used to keep meshes transformations so they can be restored
  66687. // when we build back a Babylon Mesh
  66688. // NB : All CSG operations are performed in world coordinates
  66689. CSG.prototype.copyTransformAttributes = function (csg) {
  66690. this.matrix = csg.matrix;
  66691. this.position = csg.position;
  66692. this.rotation = csg.rotation;
  66693. this.scaling = csg.scaling;
  66694. this.rotationQuaternion = csg.rotationQuaternion;
  66695. return this;
  66696. };
  66697. // Build Raw mesh from CSG
  66698. // Coordinates here are in world space
  66699. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  66700. var matrix = this.matrix.clone();
  66701. matrix.invert();
  66702. 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;
  66703. if (keepSubMeshes) {
  66704. // Sort Polygons, since subMeshes are indices range
  66705. polygons.sort(function (a, b) {
  66706. if (a.shared.meshId === b.shared.meshId) {
  66707. return a.shared.subMeshId - b.shared.subMeshId;
  66708. }
  66709. else {
  66710. return a.shared.meshId - b.shared.meshId;
  66711. }
  66712. });
  66713. }
  66714. for (var i = 0, il = polygons.length; i < il; i++) {
  66715. polygon = polygons[i];
  66716. // Building SubMeshes
  66717. if (!subMesh_dict[polygon.shared.meshId]) {
  66718. subMesh_dict[polygon.shared.meshId] = {};
  66719. }
  66720. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  66721. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  66722. indexStart: +Infinity,
  66723. indexEnd: -Infinity,
  66724. materialIndex: polygon.shared.materialIndex
  66725. };
  66726. }
  66727. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  66728. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  66729. polygonIndices[0] = 0;
  66730. polygonIndices[1] = j - 1;
  66731. polygonIndices[2] = j;
  66732. for (var k = 0; k < 3; k++) {
  66733. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  66734. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  66735. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  66736. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  66737. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  66738. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  66739. // Check if 2 points can be merged
  66740. if (!(typeof vertex_idx !== 'undefined' &&
  66741. normals[vertex_idx * 3] === localNormal.x &&
  66742. normals[vertex_idx * 3 + 1] === localNormal.y &&
  66743. normals[vertex_idx * 3 + 2] === localNormal.z &&
  66744. uvs[vertex_idx * 2] === uv.x &&
  66745. uvs[vertex_idx * 2 + 1] === uv.y)) {
  66746. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  66747. uvs.push(uv.x, uv.y);
  66748. normals.push(normal.x, normal.y, normal.z);
  66749. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  66750. }
  66751. indices.push(vertex_idx);
  66752. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  66753. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  66754. currentIndex++;
  66755. }
  66756. }
  66757. }
  66758. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  66759. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  66760. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  66761. mesh.setIndices(indices, null);
  66762. if (keepSubMeshes) {
  66763. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  66764. var materialIndexOffset = 0, materialMaxIndex;
  66765. mesh.subMeshes = new Array();
  66766. for (var m in subMesh_dict) {
  66767. materialMaxIndex = -1;
  66768. for (var sm in subMesh_dict[m]) {
  66769. subMesh_obj = subMesh_dict[m][sm];
  66770. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  66771. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  66772. }
  66773. materialIndexOffset += ++materialMaxIndex;
  66774. }
  66775. }
  66776. return mesh;
  66777. };
  66778. // Build Mesh from CSG taking material and transforms into account
  66779. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  66780. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  66781. mesh.material = material;
  66782. mesh.position.copyFrom(this.position);
  66783. mesh.rotation.copyFrom(this.rotation);
  66784. if (this.rotationQuaternion) {
  66785. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  66786. }
  66787. mesh.scaling.copyFrom(this.scaling);
  66788. mesh.computeWorldMatrix(true);
  66789. return mesh;
  66790. };
  66791. return CSG;
  66792. }());
  66793. BABYLON.CSG = CSG;
  66794. })(BABYLON || (BABYLON = {}));
  66795. //# sourceMappingURL=babylon.csg.js.map
  66796. var BABYLON;
  66797. (function (BABYLON) {
  66798. var LensFlare = /** @class */ (function () {
  66799. function LensFlare(size, position, color, imgUrl, system) {
  66800. this.size = size;
  66801. this.position = position;
  66802. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  66803. this.color = color || new BABYLON.Color3(1, 1, 1);
  66804. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  66805. this._system = system;
  66806. system.lensFlares.push(this);
  66807. }
  66808. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  66809. return new LensFlare(size, position, color, imgUrl, system);
  66810. };
  66811. LensFlare.prototype.dispose = function () {
  66812. if (this.texture) {
  66813. this.texture.dispose();
  66814. }
  66815. // Remove from scene
  66816. var index = this._system.lensFlares.indexOf(this);
  66817. this._system.lensFlares.splice(index, 1);
  66818. };
  66819. ;
  66820. return LensFlare;
  66821. }());
  66822. BABYLON.LensFlare = LensFlare;
  66823. })(BABYLON || (BABYLON = {}));
  66824. //# sourceMappingURL=babylon.lensFlare.js.map
  66825. var BABYLON;
  66826. (function (BABYLON) {
  66827. var LensFlareSystem = /** @class */ (function () {
  66828. function LensFlareSystem(name, emitter, scene) {
  66829. this.name = name;
  66830. this.lensFlares = new Array();
  66831. this.borderLimit = 300;
  66832. this.viewportBorder = 0;
  66833. this.layerMask = 0x0FFFFFFF;
  66834. this._vertexBuffers = {};
  66835. this._isEnabled = true;
  66836. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  66837. this._emitter = emitter;
  66838. this.id = name;
  66839. scene.lensFlareSystems.push(this);
  66840. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  66841. var engine = scene.getEngine();
  66842. // VBO
  66843. var vertices = [];
  66844. vertices.push(1, 1);
  66845. vertices.push(-1, 1);
  66846. vertices.push(-1, -1);
  66847. vertices.push(1, -1);
  66848. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  66849. // Indices
  66850. var indices = [];
  66851. indices.push(0);
  66852. indices.push(1);
  66853. indices.push(2);
  66854. indices.push(0);
  66855. indices.push(2);
  66856. indices.push(3);
  66857. this._indexBuffer = engine.createIndexBuffer(indices);
  66858. // Effects
  66859. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  66860. }
  66861. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  66862. get: function () {
  66863. return this._isEnabled;
  66864. },
  66865. set: function (value) {
  66866. this._isEnabled = value;
  66867. },
  66868. enumerable: true,
  66869. configurable: true
  66870. });
  66871. LensFlareSystem.prototype.getScene = function () {
  66872. return this._scene;
  66873. };
  66874. LensFlareSystem.prototype.getEmitter = function () {
  66875. return this._emitter;
  66876. };
  66877. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  66878. this._emitter = newEmitter;
  66879. };
  66880. LensFlareSystem.prototype.getEmitterPosition = function () {
  66881. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  66882. };
  66883. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  66884. var position = this.getEmitterPosition();
  66885. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  66886. this._positionX = position.x;
  66887. this._positionY = position.y;
  66888. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  66889. if (this.viewportBorder > 0) {
  66890. globalViewport.x -= this.viewportBorder;
  66891. globalViewport.y -= this.viewportBorder;
  66892. globalViewport.width += this.viewportBorder * 2;
  66893. globalViewport.height += this.viewportBorder * 2;
  66894. position.x += this.viewportBorder;
  66895. position.y += this.viewportBorder;
  66896. this._positionX += this.viewportBorder;
  66897. this._positionY += this.viewportBorder;
  66898. }
  66899. if (position.z > 0) {
  66900. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  66901. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  66902. return true;
  66903. }
  66904. return true;
  66905. }
  66906. return false;
  66907. };
  66908. LensFlareSystem.prototype._isVisible = function () {
  66909. if (!this._isEnabled || !this._scene.activeCamera) {
  66910. return false;
  66911. }
  66912. var emitterPosition = this.getEmitterPosition();
  66913. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  66914. var distance = direction.length();
  66915. direction.normalize();
  66916. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  66917. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  66918. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  66919. };
  66920. LensFlareSystem.prototype.render = function () {
  66921. if (!this._effect.isReady() || !this._scene.activeCamera)
  66922. return false;
  66923. var engine = this._scene.getEngine();
  66924. var viewport = this._scene.activeCamera.viewport;
  66925. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  66926. // Position
  66927. if (!this.computeEffectivePosition(globalViewport)) {
  66928. return false;
  66929. }
  66930. // Visibility
  66931. if (!this._isVisible()) {
  66932. return false;
  66933. }
  66934. // Intensity
  66935. var awayX;
  66936. var awayY;
  66937. if (this._positionX < this.borderLimit + globalViewport.x) {
  66938. awayX = this.borderLimit + globalViewport.x - this._positionX;
  66939. }
  66940. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  66941. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  66942. }
  66943. else {
  66944. awayX = 0;
  66945. }
  66946. if (this._positionY < this.borderLimit + globalViewport.y) {
  66947. awayY = this.borderLimit + globalViewport.y - this._positionY;
  66948. }
  66949. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  66950. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  66951. }
  66952. else {
  66953. awayY = 0;
  66954. }
  66955. var away = (awayX > awayY) ? awayX : awayY;
  66956. away -= this.viewportBorder;
  66957. if (away > this.borderLimit) {
  66958. away = this.borderLimit;
  66959. }
  66960. var intensity = 1.0 - (away / this.borderLimit);
  66961. if (intensity < 0) {
  66962. return false;
  66963. }
  66964. if (intensity > 1.0) {
  66965. intensity = 1.0;
  66966. }
  66967. if (this.viewportBorder > 0) {
  66968. globalViewport.x += this.viewportBorder;
  66969. globalViewport.y += this.viewportBorder;
  66970. globalViewport.width -= this.viewportBorder * 2;
  66971. globalViewport.height -= this.viewportBorder * 2;
  66972. this._positionX -= this.viewportBorder;
  66973. this._positionY -= this.viewportBorder;
  66974. }
  66975. // Position
  66976. var centerX = globalViewport.x + globalViewport.width / 2;
  66977. var centerY = globalViewport.y + globalViewport.height / 2;
  66978. var distX = centerX - this._positionX;
  66979. var distY = centerY - this._positionY;
  66980. // Effects
  66981. engine.enableEffect(this._effect);
  66982. engine.setState(false);
  66983. engine.setDepthBuffer(false);
  66984. // VBOs
  66985. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  66986. // Flares
  66987. for (var index = 0; index < this.lensFlares.length; index++) {
  66988. var flare = this.lensFlares[index];
  66989. engine.setAlphaMode(flare.alphaMode);
  66990. var x = centerX - (distX * flare.position);
  66991. var y = centerY - (distY * flare.position);
  66992. var cw = flare.size;
  66993. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  66994. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  66995. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  66996. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  66997. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  66998. // Texture
  66999. this._effect.setTexture("textureSampler", flare.texture);
  67000. // Color
  67001. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  67002. // Draw order
  67003. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  67004. }
  67005. engine.setDepthBuffer(true);
  67006. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  67007. return true;
  67008. };
  67009. LensFlareSystem.prototype.dispose = function () {
  67010. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  67011. if (vertexBuffer) {
  67012. vertexBuffer.dispose();
  67013. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  67014. }
  67015. if (this._indexBuffer) {
  67016. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  67017. this._indexBuffer = null;
  67018. }
  67019. while (this.lensFlares.length) {
  67020. this.lensFlares[0].dispose();
  67021. }
  67022. // Remove from scene
  67023. var index = this._scene.lensFlareSystems.indexOf(this);
  67024. this._scene.lensFlareSystems.splice(index, 1);
  67025. };
  67026. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  67027. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  67028. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  67029. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  67030. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  67031. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  67032. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  67033. var parsedFlare = parsedLensFlareSystem.flares[index];
  67034. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  67035. }
  67036. return lensFlareSystem;
  67037. };
  67038. LensFlareSystem.prototype.serialize = function () {
  67039. var serializationObject = {};
  67040. serializationObject.id = this.id;
  67041. serializationObject.name = this.name;
  67042. serializationObject.emitterId = this.getEmitter().id;
  67043. serializationObject.borderLimit = this.borderLimit;
  67044. serializationObject.flares = [];
  67045. for (var index = 0; index < this.lensFlares.length; index++) {
  67046. var flare = this.lensFlares[index];
  67047. serializationObject.flares.push({
  67048. size: flare.size,
  67049. position: flare.position,
  67050. color: flare.color.asArray(),
  67051. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  67052. });
  67053. }
  67054. return serializationObject;
  67055. };
  67056. return LensFlareSystem;
  67057. }());
  67058. BABYLON.LensFlareSystem = LensFlareSystem;
  67059. })(BABYLON || (BABYLON = {}));
  67060. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  67061. var BABYLON;
  67062. (function (BABYLON) {
  67063. /**
  67064. * This is a holder class for the physics joint created by the physics plugin.
  67065. * It holds a set of functions to control the underlying joint.
  67066. */
  67067. var PhysicsJoint = /** @class */ (function () {
  67068. function PhysicsJoint(type, jointData) {
  67069. this.type = type;
  67070. this.jointData = jointData;
  67071. jointData.nativeParams = jointData.nativeParams || {};
  67072. }
  67073. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  67074. get: function () {
  67075. return this._physicsJoint;
  67076. },
  67077. set: function (newJoint) {
  67078. if (this._physicsJoint) {
  67079. //remove from the wolrd
  67080. }
  67081. this._physicsJoint = newJoint;
  67082. },
  67083. enumerable: true,
  67084. configurable: true
  67085. });
  67086. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  67087. set: function (physicsPlugin) {
  67088. this._physicsPlugin = physicsPlugin;
  67089. },
  67090. enumerable: true,
  67091. configurable: true
  67092. });
  67093. /**
  67094. * Execute a function that is physics-plugin specific.
  67095. * @param {Function} func the function that will be executed.
  67096. * It accepts two parameters: the physics world and the physics joint.
  67097. */
  67098. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  67099. func(this._physicsPlugin.world, this._physicsJoint);
  67100. };
  67101. //TODO check if the native joints are the same
  67102. //Joint Types
  67103. PhysicsJoint.DistanceJoint = 0;
  67104. PhysicsJoint.HingeJoint = 1;
  67105. PhysicsJoint.BallAndSocketJoint = 2;
  67106. PhysicsJoint.WheelJoint = 3;
  67107. PhysicsJoint.SliderJoint = 4;
  67108. //OIMO
  67109. PhysicsJoint.PrismaticJoint = 5;
  67110. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  67111. PhysicsJoint.UniversalJoint = 6;
  67112. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  67113. //Cannon
  67114. //Similar to a Ball-Joint. Different in params
  67115. PhysicsJoint.PointToPointJoint = 8;
  67116. //Cannon only at the moment
  67117. PhysicsJoint.SpringJoint = 9;
  67118. PhysicsJoint.LockJoint = 10;
  67119. return PhysicsJoint;
  67120. }());
  67121. BABYLON.PhysicsJoint = PhysicsJoint;
  67122. /**
  67123. * A class representing a physics distance joint.
  67124. */
  67125. var DistanceJoint = /** @class */ (function (_super) {
  67126. __extends(DistanceJoint, _super);
  67127. function DistanceJoint(jointData) {
  67128. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  67129. }
  67130. /**
  67131. * Update the predefined distance.
  67132. */
  67133. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  67134. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  67135. };
  67136. return DistanceJoint;
  67137. }(PhysicsJoint));
  67138. BABYLON.DistanceJoint = DistanceJoint;
  67139. var MotorEnabledJoint = /** @class */ (function (_super) {
  67140. __extends(MotorEnabledJoint, _super);
  67141. function MotorEnabledJoint(type, jointData) {
  67142. return _super.call(this, type, jointData) || this;
  67143. }
  67144. /**
  67145. * Set the motor values.
  67146. * Attention, this function is plugin specific. Engines won't react 100% the same.
  67147. * @param {number} force the force to apply
  67148. * @param {number} maxForce max force for this motor.
  67149. */
  67150. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  67151. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  67152. };
  67153. /**
  67154. * Set the motor's limits.
  67155. * Attention, this function is plugin specific. Engines won't react 100% the same.
  67156. */
  67157. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  67158. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  67159. };
  67160. return MotorEnabledJoint;
  67161. }(PhysicsJoint));
  67162. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  67163. /**
  67164. * This class represents a single hinge physics joint
  67165. */
  67166. var HingeJoint = /** @class */ (function (_super) {
  67167. __extends(HingeJoint, _super);
  67168. function HingeJoint(jointData) {
  67169. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  67170. }
  67171. /**
  67172. * Set the motor values.
  67173. * Attention, this function is plugin specific. Engines won't react 100% the same.
  67174. * @param {number} force the force to apply
  67175. * @param {number} maxForce max force for this motor.
  67176. */
  67177. HingeJoint.prototype.setMotor = function (force, maxForce) {
  67178. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  67179. };
  67180. /**
  67181. * Set the motor's limits.
  67182. * Attention, this function is plugin specific. Engines won't react 100% the same.
  67183. */
  67184. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  67185. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  67186. };
  67187. return HingeJoint;
  67188. }(MotorEnabledJoint));
  67189. BABYLON.HingeJoint = HingeJoint;
  67190. /**
  67191. * This class represents a dual hinge physics joint (same as wheel joint)
  67192. */
  67193. var Hinge2Joint = /** @class */ (function (_super) {
  67194. __extends(Hinge2Joint, _super);
  67195. function Hinge2Joint(jointData) {
  67196. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  67197. }
  67198. /**
  67199. * Set the motor values.
  67200. * Attention, this function is plugin specific. Engines won't react 100% the same.
  67201. * @param {number} force the force to apply
  67202. * @param {number} maxForce max force for this motor.
  67203. * @param {motorIndex} the motor's index, 0 or 1.
  67204. */
  67205. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  67206. if (motorIndex === void 0) { motorIndex = 0; }
  67207. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  67208. };
  67209. /**
  67210. * Set the motor limits.
  67211. * Attention, this function is plugin specific. Engines won't react 100% the same.
  67212. * @param {number} upperLimit the upper limit
  67213. * @param {number} lowerLimit lower limit
  67214. * @param {motorIndex} the motor's index, 0 or 1.
  67215. */
  67216. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  67217. if (motorIndex === void 0) { motorIndex = 0; }
  67218. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  67219. };
  67220. return Hinge2Joint;
  67221. }(MotorEnabledJoint));
  67222. BABYLON.Hinge2Joint = Hinge2Joint;
  67223. })(BABYLON || (BABYLON = {}));
  67224. //# sourceMappingURL=babylon.physicsJoint.js.map
  67225. var BABYLON;
  67226. (function (BABYLON) {
  67227. var PhysicsImpostor = /** @class */ (function () {
  67228. function PhysicsImpostor(object, type, _options, _scene) {
  67229. if (_options === void 0) { _options = { mass: 0 }; }
  67230. var _this = this;
  67231. this.object = object;
  67232. this.type = type;
  67233. this._options = _options;
  67234. this._scene = _scene;
  67235. this._bodyUpdateRequired = false;
  67236. this._onBeforePhysicsStepCallbacks = new Array();
  67237. this._onAfterPhysicsStepCallbacks = new Array();
  67238. this._onPhysicsCollideCallbacks = [];
  67239. this._deltaPosition = BABYLON.Vector3.Zero();
  67240. this._isDisposed = false;
  67241. //temp variables for parent rotation calculations
  67242. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  67243. this._tmpQuat = new BABYLON.Quaternion();
  67244. this._tmpQuat2 = new BABYLON.Quaternion();
  67245. /**
  67246. * this function is executed by the physics engine.
  67247. */
  67248. this.beforeStep = function () {
  67249. if (!_this._physicsEngine) {
  67250. return;
  67251. }
  67252. _this.object.translate(_this._deltaPosition, -1);
  67253. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  67254. _this.object.computeWorldMatrix(false);
  67255. if (_this.object.parent && _this.object.rotationQuaternion) {
  67256. _this.getParentsRotation();
  67257. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  67258. }
  67259. else {
  67260. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  67261. }
  67262. if (!_this._options.disableBidirectionalTransformation) {
  67263. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  67264. }
  67265. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  67266. func(_this);
  67267. });
  67268. };
  67269. /**
  67270. * this function is executed by the physics engine.
  67271. */
  67272. this.afterStep = function () {
  67273. if (!_this._physicsEngine) {
  67274. return;
  67275. }
  67276. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  67277. func(_this);
  67278. });
  67279. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  67280. // object has now its world rotation. needs to be converted to local.
  67281. if (_this.object.parent && _this.object.rotationQuaternion) {
  67282. _this.getParentsRotation();
  67283. _this._tmpQuat.conjugateInPlace();
  67284. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  67285. }
  67286. // take the position set and make it the absolute position of this object.
  67287. _this.object.setAbsolutePosition(_this.object.position);
  67288. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  67289. _this.object.translate(_this._deltaPosition, 1);
  67290. };
  67291. /**
  67292. * Legacy collision detection event support
  67293. */
  67294. this.onCollideEvent = null;
  67295. //event and body object due to cannon's event-based architecture.
  67296. this.onCollide = function (e) {
  67297. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  67298. return;
  67299. }
  67300. if (!_this._physicsEngine) {
  67301. return;
  67302. }
  67303. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  67304. if (otherImpostor) {
  67305. // Legacy collision detection event support
  67306. if (_this.onCollideEvent) {
  67307. _this.onCollideEvent(_this, otherImpostor);
  67308. }
  67309. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  67310. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  67311. }).forEach(function (obj) {
  67312. obj.callback(_this, otherImpostor);
  67313. });
  67314. }
  67315. };
  67316. //sanity check!
  67317. if (!this.object) {
  67318. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  67319. return;
  67320. }
  67321. //legacy support for old syntax.
  67322. if (!this._scene && object.getScene) {
  67323. this._scene = object.getScene();
  67324. }
  67325. if (!this._scene) {
  67326. return;
  67327. }
  67328. this._physicsEngine = this._scene.getPhysicsEngine();
  67329. if (!this._physicsEngine) {
  67330. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  67331. }
  67332. else {
  67333. //set the object's quaternion, if not set
  67334. if (!this.object.rotationQuaternion) {
  67335. if (this.object.rotation) {
  67336. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  67337. }
  67338. else {
  67339. this.object.rotationQuaternion = new BABYLON.Quaternion();
  67340. }
  67341. }
  67342. //default options params
  67343. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  67344. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  67345. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  67346. this._joints = [];
  67347. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  67348. if (!this.object.parent || this._options.ignoreParent) {
  67349. this._init();
  67350. }
  67351. else if (this.object.parent.physicsImpostor) {
  67352. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  67353. }
  67354. }
  67355. }
  67356. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  67357. get: function () {
  67358. return this._isDisposed;
  67359. },
  67360. enumerable: true,
  67361. configurable: true
  67362. });
  67363. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  67364. get: function () {
  67365. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  67366. },
  67367. set: function (value) {
  67368. this.setMass(value);
  67369. },
  67370. enumerable: true,
  67371. configurable: true
  67372. });
  67373. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  67374. get: function () {
  67375. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  67376. },
  67377. set: function (value) {
  67378. if (!this._physicsEngine) {
  67379. return;
  67380. }
  67381. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  67382. },
  67383. enumerable: true,
  67384. configurable: true
  67385. });
  67386. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  67387. get: function () {
  67388. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  67389. },
  67390. set: function (value) {
  67391. if (!this._physicsEngine) {
  67392. return;
  67393. }
  67394. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  67395. },
  67396. enumerable: true,
  67397. configurable: true
  67398. });
  67399. /**
  67400. * This function will completly initialize this impostor.
  67401. * It will create a new body - but only if this mesh has no parent.
  67402. * If it has, this impostor will not be used other than to define the impostor
  67403. * of the child mesh.
  67404. */
  67405. PhysicsImpostor.prototype._init = function () {
  67406. if (!this._physicsEngine) {
  67407. return;
  67408. }
  67409. this._physicsEngine.removeImpostor(this);
  67410. this.physicsBody = null;
  67411. this._parent = this._parent || this._getPhysicsParent();
  67412. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  67413. this._physicsEngine.addImpostor(this);
  67414. }
  67415. };
  67416. PhysicsImpostor.prototype._getPhysicsParent = function () {
  67417. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  67418. var parentMesh = this.object.parent;
  67419. return parentMesh.physicsImpostor;
  67420. }
  67421. return null;
  67422. };
  67423. /**
  67424. * Should a new body be generated.
  67425. */
  67426. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  67427. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  67428. };
  67429. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  67430. this.forceUpdate();
  67431. };
  67432. /**
  67433. * Force a regeneration of this or the parent's impostor's body.
  67434. * Use under cautious - This will remove all joints already implemented.
  67435. */
  67436. PhysicsImpostor.prototype.forceUpdate = function () {
  67437. this._init();
  67438. if (this.parent && !this._options.ignoreParent) {
  67439. this.parent.forceUpdate();
  67440. }
  67441. };
  67442. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  67443. /*public get mesh(): AbstractMesh {
  67444. return this._mesh;
  67445. }*/
  67446. /**
  67447. * Gets the body that holds this impostor. Either its own, or its parent.
  67448. */
  67449. get: function () {
  67450. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  67451. },
  67452. /**
  67453. * Set the physics body. Used mainly by the physics engine/plugin
  67454. */
  67455. set: function (physicsBody) {
  67456. if (this._physicsBody && this._physicsEngine) {
  67457. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  67458. }
  67459. this._physicsBody = physicsBody;
  67460. this.resetUpdateFlags();
  67461. },
  67462. enumerable: true,
  67463. configurable: true
  67464. });
  67465. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  67466. get: function () {
  67467. return !this._options.ignoreParent && this._parent ? this._parent : null;
  67468. },
  67469. set: function (value) {
  67470. this._parent = value;
  67471. },
  67472. enumerable: true,
  67473. configurable: true
  67474. });
  67475. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  67476. this._bodyUpdateRequired = false;
  67477. };
  67478. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  67479. if (this.object.getBoundingInfo) {
  67480. var q = this.object.rotationQuaternion;
  67481. //reset rotation
  67482. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  67483. //calculate the world matrix with no rotation
  67484. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  67485. var boundingInfo = this.object.getBoundingInfo();
  67486. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  67487. //bring back the rotation
  67488. this.object.rotationQuaternion = q;
  67489. //calculate the world matrix with the new rotation
  67490. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  67491. return size;
  67492. }
  67493. else {
  67494. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  67495. }
  67496. };
  67497. PhysicsImpostor.prototype.getObjectCenter = function () {
  67498. if (this.object.getBoundingInfo) {
  67499. var boundingInfo = this.object.getBoundingInfo();
  67500. return boundingInfo.boundingBox.centerWorld;
  67501. }
  67502. else {
  67503. return this.object.position;
  67504. }
  67505. };
  67506. /**
  67507. * Get a specific parametes from the options parameter.
  67508. */
  67509. PhysicsImpostor.prototype.getParam = function (paramName) {
  67510. return this._options[paramName];
  67511. };
  67512. /**
  67513. * Sets a specific parameter in the options given to the physics plugin
  67514. */
  67515. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  67516. this._options[paramName] = value;
  67517. this._bodyUpdateRequired = true;
  67518. };
  67519. /**
  67520. * Specifically change the body's mass option. Won't recreate the physics body object
  67521. */
  67522. PhysicsImpostor.prototype.setMass = function (mass) {
  67523. if (this.getParam("mass") !== mass) {
  67524. this.setParam("mass", mass);
  67525. }
  67526. if (this._physicsEngine) {
  67527. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  67528. }
  67529. };
  67530. PhysicsImpostor.prototype.getLinearVelocity = function () {
  67531. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  67532. };
  67533. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  67534. if (this._physicsEngine) {
  67535. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  67536. }
  67537. };
  67538. PhysicsImpostor.prototype.getAngularVelocity = function () {
  67539. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  67540. };
  67541. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  67542. if (this._physicsEngine) {
  67543. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  67544. }
  67545. };
  67546. /**
  67547. * Execute a function with the physics plugin native code.
  67548. * Provide a function the will have two variables - the world object and the physics body object.
  67549. */
  67550. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  67551. if (this._physicsEngine) {
  67552. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  67553. }
  67554. };
  67555. /**
  67556. * Register a function that will be executed before the physics world is stepping forward.
  67557. */
  67558. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  67559. this._onBeforePhysicsStepCallbacks.push(func);
  67560. };
  67561. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  67562. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  67563. if (index > -1) {
  67564. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  67565. }
  67566. else {
  67567. BABYLON.Tools.Warn("Function to remove was not found");
  67568. }
  67569. };
  67570. /**
  67571. * Register a function that will be executed after the physics step
  67572. */
  67573. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  67574. this._onAfterPhysicsStepCallbacks.push(func);
  67575. };
  67576. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  67577. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  67578. if (index > -1) {
  67579. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  67580. }
  67581. else {
  67582. BABYLON.Tools.Warn("Function to remove was not found");
  67583. }
  67584. };
  67585. /**
  67586. * register a function that will be executed when this impostor collides against a different body.
  67587. */
  67588. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  67589. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  67590. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  67591. };
  67592. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  67593. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  67594. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  67595. if (index > -1) {
  67596. this._onPhysicsCollideCallbacks.splice(index, 1);
  67597. }
  67598. else {
  67599. BABYLON.Tools.Warn("Function to remove was not found");
  67600. }
  67601. };
  67602. PhysicsImpostor.prototype.getParentsRotation = function () {
  67603. var parent = this.object.parent;
  67604. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  67605. while (parent) {
  67606. if (parent.rotationQuaternion) {
  67607. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  67608. }
  67609. else {
  67610. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  67611. }
  67612. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  67613. parent = parent.parent;
  67614. }
  67615. return this._tmpQuat;
  67616. };
  67617. /**
  67618. * Apply a force
  67619. */
  67620. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  67621. if (this._physicsEngine) {
  67622. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  67623. }
  67624. return this;
  67625. };
  67626. /**
  67627. * Apply an impulse
  67628. */
  67629. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  67630. if (this._physicsEngine) {
  67631. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  67632. }
  67633. return this;
  67634. };
  67635. /**
  67636. * A help function to create a joint.
  67637. */
  67638. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  67639. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  67640. this.addJoint(otherImpostor, joint);
  67641. return this;
  67642. };
  67643. /**
  67644. * Add a joint to this impostor with a different impostor.
  67645. */
  67646. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  67647. this._joints.push({
  67648. otherImpostor: otherImpostor,
  67649. joint: joint
  67650. });
  67651. if (this._physicsEngine) {
  67652. this._physicsEngine.addJoint(this, otherImpostor, joint);
  67653. }
  67654. return this;
  67655. };
  67656. /**
  67657. * Will keep this body still, in a sleep mode.
  67658. */
  67659. PhysicsImpostor.prototype.sleep = function () {
  67660. if (this._physicsEngine) {
  67661. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  67662. }
  67663. return this;
  67664. };
  67665. /**
  67666. * Wake the body up.
  67667. */
  67668. PhysicsImpostor.prototype.wakeUp = function () {
  67669. if (this._physicsEngine) {
  67670. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  67671. }
  67672. return this;
  67673. };
  67674. PhysicsImpostor.prototype.clone = function (newObject) {
  67675. if (!newObject)
  67676. return null;
  67677. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  67678. };
  67679. PhysicsImpostor.prototype.dispose = function () {
  67680. var _this = this;
  67681. //no dispose if no physics engine is available.
  67682. if (!this._physicsEngine) {
  67683. return;
  67684. }
  67685. this._joints.forEach(function (j) {
  67686. if (_this._physicsEngine) {
  67687. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  67688. }
  67689. });
  67690. //dispose the physics body
  67691. this._physicsEngine.removeImpostor(this);
  67692. if (this.parent) {
  67693. this.parent.forceUpdate();
  67694. }
  67695. else {
  67696. /*this._object.getChildMeshes().forEach(function(mesh) {
  67697. if (mesh.physicsImpostor) {
  67698. if (disposeChildren) {
  67699. mesh.physicsImpostor.dispose();
  67700. mesh.physicsImpostor = null;
  67701. }
  67702. }
  67703. })*/
  67704. }
  67705. this._isDisposed = true;
  67706. };
  67707. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  67708. this._deltaPosition.copyFrom(position);
  67709. };
  67710. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  67711. if (!this._deltaRotation) {
  67712. this._deltaRotation = new BABYLON.Quaternion();
  67713. }
  67714. this._deltaRotation.copyFrom(rotation);
  67715. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  67716. };
  67717. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  67718. if (this._physicsEngine) {
  67719. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  67720. }
  67721. return this;
  67722. };
  67723. PhysicsImpostor.prototype.getRadius = function () {
  67724. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  67725. };
  67726. /**
  67727. * Sync a bone with this impostor
  67728. * @param bone The bone to sync to the impostor.
  67729. * @param boneMesh The mesh that the bone is influencing.
  67730. * @param jointPivot The pivot of the joint / bone in local space.
  67731. * @param distToJoint Optional distance from the impostor to the joint.
  67732. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  67733. */
  67734. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  67735. var tempVec = PhysicsImpostor._tmpVecs[0];
  67736. var mesh = this.object;
  67737. if (mesh.rotationQuaternion) {
  67738. if (adjustRotation) {
  67739. var tempQuat = PhysicsImpostor._tmpQuat;
  67740. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  67741. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  67742. }
  67743. else {
  67744. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  67745. }
  67746. }
  67747. tempVec.x = 0;
  67748. tempVec.y = 0;
  67749. tempVec.z = 0;
  67750. if (jointPivot) {
  67751. tempVec.x = jointPivot.x;
  67752. tempVec.y = jointPivot.y;
  67753. tempVec.z = jointPivot.z;
  67754. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  67755. if (distToJoint === undefined || distToJoint === null) {
  67756. distToJoint = jointPivot.length();
  67757. }
  67758. tempVec.x *= distToJoint;
  67759. tempVec.y *= distToJoint;
  67760. tempVec.z *= distToJoint;
  67761. }
  67762. if (bone.getParent()) {
  67763. tempVec.addInPlace(mesh.getAbsolutePosition());
  67764. bone.setAbsolutePosition(tempVec, boneMesh);
  67765. }
  67766. else {
  67767. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  67768. boneMesh.position.x -= tempVec.x;
  67769. boneMesh.position.y -= tempVec.y;
  67770. boneMesh.position.z -= tempVec.z;
  67771. }
  67772. };
  67773. /**
  67774. * Sync impostor to a bone
  67775. * @param bone The bone that the impostor will be synced to.
  67776. * @param boneMesh The mesh that the bone is influencing.
  67777. * @param jointPivot The pivot of the joint / bone in local space.
  67778. * @param distToJoint Optional distance from the impostor to the joint.
  67779. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  67780. * @param boneAxis Optional vector3 axis the bone is aligned with
  67781. */
  67782. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  67783. var mesh = this.object;
  67784. if (mesh.rotationQuaternion) {
  67785. if (adjustRotation) {
  67786. var tempQuat = PhysicsImpostor._tmpQuat;
  67787. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  67788. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  67789. }
  67790. else {
  67791. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  67792. }
  67793. }
  67794. var pos = PhysicsImpostor._tmpVecs[0];
  67795. var boneDir = PhysicsImpostor._tmpVecs[1];
  67796. if (!boneAxis) {
  67797. boneAxis = PhysicsImpostor._tmpVecs[2];
  67798. boneAxis.x = 0;
  67799. boneAxis.y = 1;
  67800. boneAxis.z = 0;
  67801. }
  67802. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  67803. bone.getAbsolutePositionToRef(boneMesh, pos);
  67804. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  67805. distToJoint = jointPivot.length();
  67806. }
  67807. if (distToJoint !== undefined && distToJoint !== null) {
  67808. pos.x += boneDir.x * distToJoint;
  67809. pos.y += boneDir.y * distToJoint;
  67810. pos.z += boneDir.z * distToJoint;
  67811. }
  67812. mesh.setAbsolutePosition(pos);
  67813. };
  67814. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  67815. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  67816. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  67817. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  67818. //Impostor types
  67819. PhysicsImpostor.NoImpostor = 0;
  67820. PhysicsImpostor.SphereImpostor = 1;
  67821. PhysicsImpostor.BoxImpostor = 2;
  67822. PhysicsImpostor.PlaneImpostor = 3;
  67823. PhysicsImpostor.MeshImpostor = 4;
  67824. PhysicsImpostor.CylinderImpostor = 7;
  67825. PhysicsImpostor.ParticleImpostor = 8;
  67826. PhysicsImpostor.HeightmapImpostor = 9;
  67827. return PhysicsImpostor;
  67828. }());
  67829. BABYLON.PhysicsImpostor = PhysicsImpostor;
  67830. })(BABYLON || (BABYLON = {}));
  67831. //# sourceMappingURL=babylon.physicsImpostor.js.map
  67832. var BABYLON;
  67833. (function (BABYLON) {
  67834. var PhysicsEngine = /** @class */ (function () {
  67835. function PhysicsEngine(gravity, _physicsPlugin) {
  67836. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  67837. this._physicsPlugin = _physicsPlugin;
  67838. //new methods and parameters
  67839. this._impostors = [];
  67840. this._joints = [];
  67841. if (!this._physicsPlugin.isSupported()) {
  67842. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  67843. + "Please make sure it is included.");
  67844. }
  67845. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  67846. this.setGravity(gravity);
  67847. this.setTimeStep();
  67848. }
  67849. PhysicsEngine.prototype.setGravity = function (gravity) {
  67850. this.gravity = gravity;
  67851. this._physicsPlugin.setGravity(this.gravity);
  67852. };
  67853. /**
  67854. * Set the time step of the physics engine.
  67855. * default is 1/60.
  67856. * To slow it down, enter 1/600 for example.
  67857. * To speed it up, 1/30
  67858. * @param {number} newTimeStep the new timestep to apply to this world.
  67859. */
  67860. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  67861. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  67862. this._physicsPlugin.setTimeStep(newTimeStep);
  67863. };
  67864. /**
  67865. * Get the time step of the physics engine.
  67866. */
  67867. PhysicsEngine.prototype.getTimeStep = function () {
  67868. return this._physicsPlugin.getTimeStep();
  67869. };
  67870. PhysicsEngine.prototype.dispose = function () {
  67871. this._impostors.forEach(function (impostor) {
  67872. impostor.dispose();
  67873. });
  67874. this._physicsPlugin.dispose();
  67875. };
  67876. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  67877. return this._physicsPlugin.name;
  67878. };
  67879. /**
  67880. * Adding a new impostor for the impostor tracking.
  67881. * This will be done by the impostor itself.
  67882. * @param {PhysicsImpostor} impostor the impostor to add
  67883. */
  67884. PhysicsEngine.prototype.addImpostor = function (impostor) {
  67885. impostor.uniqueId = this._impostors.push(impostor);
  67886. //if no parent, generate the body
  67887. if (!impostor.parent) {
  67888. this._physicsPlugin.generatePhysicsBody(impostor);
  67889. }
  67890. };
  67891. /**
  67892. * Remove an impostor from the engine.
  67893. * This impostor and its mesh will not longer be updated by the physics engine.
  67894. * @param {PhysicsImpostor} impostor the impostor to remove
  67895. */
  67896. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  67897. var index = this._impostors.indexOf(impostor);
  67898. if (index > -1) {
  67899. var removed = this._impostors.splice(index, 1);
  67900. //Is it needed?
  67901. if (removed.length) {
  67902. //this will also remove it from the world.
  67903. removed[0].physicsBody = null;
  67904. }
  67905. }
  67906. };
  67907. /**
  67908. * Add a joint to the physics engine
  67909. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  67910. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  67911. * @param {PhysicsJoint} the joint that will connect both impostors.
  67912. */
  67913. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  67914. var impostorJoint = {
  67915. mainImpostor: mainImpostor,
  67916. connectedImpostor: connectedImpostor,
  67917. joint: joint
  67918. };
  67919. joint.physicsPlugin = this._physicsPlugin;
  67920. this._joints.push(impostorJoint);
  67921. this._physicsPlugin.generateJoint(impostorJoint);
  67922. };
  67923. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  67924. var matchingJoints = this._joints.filter(function (impostorJoint) {
  67925. return (impostorJoint.connectedImpostor === connectedImpostor
  67926. && impostorJoint.joint === joint
  67927. && impostorJoint.mainImpostor === mainImpostor);
  67928. });
  67929. if (matchingJoints.length) {
  67930. this._physicsPlugin.removeJoint(matchingJoints[0]);
  67931. //TODO remove it from the list as well
  67932. }
  67933. };
  67934. /**
  67935. * Called by the scene. no need to call it.
  67936. */
  67937. PhysicsEngine.prototype._step = function (delta) {
  67938. var _this = this;
  67939. //check if any mesh has no body / requires an update
  67940. this._impostors.forEach(function (impostor) {
  67941. if (impostor.isBodyInitRequired()) {
  67942. _this._physicsPlugin.generatePhysicsBody(impostor);
  67943. }
  67944. });
  67945. if (delta > 0.1) {
  67946. delta = 0.1;
  67947. }
  67948. else if (delta <= 0) {
  67949. delta = 1.0 / 60.0;
  67950. }
  67951. this._physicsPlugin.executeStep(delta, this._impostors);
  67952. };
  67953. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  67954. return this._physicsPlugin;
  67955. };
  67956. PhysicsEngine.prototype.getImpostors = function () {
  67957. return this._impostors;
  67958. };
  67959. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  67960. for (var i = 0; i < this._impostors.length; ++i) {
  67961. if (this._impostors[i].object === object) {
  67962. return this._impostors[i];
  67963. }
  67964. }
  67965. return null;
  67966. };
  67967. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  67968. for (var i = 0; i < this._impostors.length; ++i) {
  67969. if (this._impostors[i].physicsBody === body) {
  67970. return this._impostors[i];
  67971. }
  67972. }
  67973. return null;
  67974. };
  67975. // Statics
  67976. PhysicsEngine.Epsilon = 0.001;
  67977. return PhysicsEngine;
  67978. }());
  67979. BABYLON.PhysicsEngine = PhysicsEngine;
  67980. })(BABYLON || (BABYLON = {}));
  67981. //# sourceMappingURL=babylon.physicsEngine.js.map
  67982. var BABYLON;
  67983. (function (BABYLON) {
  67984. var PhysicsHelper = /** @class */ (function () {
  67985. function PhysicsHelper(scene) {
  67986. this._scene = scene;
  67987. this._physicsEngine = this._scene.getPhysicsEngine();
  67988. if (!this._physicsEngine) {
  67989. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  67990. }
  67991. }
  67992. /**
  67993. * @param {Vector3} origin the origin of the explosion
  67994. * @param {number} radius the explosion radius
  67995. * @param {number} strength the explosion strength
  67996. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  67997. */
  67998. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  67999. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  68000. if (!this._physicsEngine) {
  68001. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  68002. return null;
  68003. }
  68004. var impostors = this._physicsEngine.getImpostors();
  68005. if (impostors.length === 0) {
  68006. return null;
  68007. }
  68008. var event = new PhysicsRadialExplosionEvent(this._scene);
  68009. impostors.forEach(function (impostor) {
  68010. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  68011. if (!impostorForceAndContactPoint) {
  68012. return;
  68013. }
  68014. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  68015. });
  68016. event.dispose(false);
  68017. return event;
  68018. };
  68019. /**
  68020. * @param {Vector3} origin the origin of the explosion
  68021. * @param {number} radius the explosion radius
  68022. * @param {number} strength the explosion strength
  68023. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  68024. */
  68025. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  68026. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  68027. if (!this._physicsEngine) {
  68028. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  68029. return null;
  68030. }
  68031. var impostors = this._physicsEngine.getImpostors();
  68032. if (impostors.length === 0) {
  68033. return null;
  68034. }
  68035. var event = new PhysicsRadialExplosionEvent(this._scene);
  68036. impostors.forEach(function (impostor) {
  68037. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  68038. if (!impostorForceAndContactPoint) {
  68039. return;
  68040. }
  68041. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  68042. });
  68043. event.dispose(false);
  68044. return event;
  68045. };
  68046. /**
  68047. * @param {Vector3} origin the origin of the explosion
  68048. * @param {number} radius the explosion radius
  68049. * @param {number} strength the explosion strength
  68050. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  68051. */
  68052. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  68053. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  68054. if (!this._physicsEngine) {
  68055. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  68056. return null;
  68057. }
  68058. var impostors = this._physicsEngine.getImpostors();
  68059. if (impostors.length === 0) {
  68060. return null;
  68061. }
  68062. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  68063. event.dispose(false);
  68064. return event;
  68065. };
  68066. /**
  68067. * @param {Vector3} origin the origin of the updraft
  68068. * @param {number} radius the radius of the updraft
  68069. * @param {number} strength the strength of the updraft
  68070. * @param {number} height the height of the updraft
  68071. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  68072. */
  68073. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  68074. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  68075. if (!this._physicsEngine) {
  68076. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  68077. return null;
  68078. }
  68079. if (this._physicsEngine.getImpostors().length === 0) {
  68080. return null;
  68081. }
  68082. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  68083. event.dispose(false);
  68084. return event;
  68085. };
  68086. /**
  68087. * @param {Vector3} origin the of the vortex
  68088. * @param {number} radius the radius of the vortex
  68089. * @param {number} strength the strength of the vortex
  68090. * @param {number} height the height of the vortex
  68091. */
  68092. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  68093. if (!this._physicsEngine) {
  68094. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  68095. return null;
  68096. }
  68097. if (this._physicsEngine.getImpostors().length === 0) {
  68098. return null;
  68099. }
  68100. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  68101. event.dispose(false);
  68102. return event;
  68103. };
  68104. return PhysicsHelper;
  68105. }());
  68106. BABYLON.PhysicsHelper = PhysicsHelper;
  68107. /***** Radial explosion *****/
  68108. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  68109. function PhysicsRadialExplosionEvent(scene) {
  68110. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  68111. this._rays = [];
  68112. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  68113. this._scene = scene;
  68114. }
  68115. /**
  68116. * Returns the data related to the radial explosion event (sphere & rays).
  68117. * @returns {PhysicsRadialExplosionEventData}
  68118. */
  68119. PhysicsRadialExplosionEvent.prototype.getData = function () {
  68120. this._dataFetched = true;
  68121. return {
  68122. sphere: this._sphere,
  68123. rays: this._rays,
  68124. };
  68125. };
  68126. /**
  68127. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  68128. * @param impostor
  68129. * @param {Vector3} origin the origin of the explosion
  68130. * @param {number} radius the explosion radius
  68131. * @param {number} strength the explosion strength
  68132. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  68133. * @returns {Nullable<PhysicsForceAndContactPoint>}
  68134. */
  68135. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  68136. if (impostor.mass === 0) {
  68137. return null;
  68138. }
  68139. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  68140. return null;
  68141. }
  68142. if (impostor.object.getClassName() !== 'Mesh') {
  68143. return null;
  68144. }
  68145. var impostorObject = impostor.object;
  68146. var impostorObjectCenter = impostor.getObjectCenter();
  68147. var direction = impostorObjectCenter.subtract(origin);
  68148. var ray = new BABYLON.Ray(origin, direction, radius);
  68149. this._rays.push(ray);
  68150. var hit = ray.intersectsMesh(impostorObject);
  68151. var contactPoint = hit.pickedPoint;
  68152. if (!contactPoint) {
  68153. return null;
  68154. }
  68155. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  68156. if (distanceFromOrigin > radius) {
  68157. return null;
  68158. }
  68159. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  68160. ? strength
  68161. : strength * (1 - (distanceFromOrigin / radius));
  68162. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  68163. return { force: force, contactPoint: contactPoint };
  68164. };
  68165. /**
  68166. * Disposes the sphere.
  68167. * @param {bolean} force
  68168. */
  68169. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  68170. var _this = this;
  68171. if (force === void 0) { force = true; }
  68172. if (force) {
  68173. this._sphere.dispose();
  68174. }
  68175. else {
  68176. setTimeout(function () {
  68177. if (!_this._dataFetched) {
  68178. _this._sphere.dispose();
  68179. }
  68180. }, 0);
  68181. }
  68182. };
  68183. /*** Helpers ***/
  68184. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  68185. if (!this._sphere) {
  68186. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  68187. this._sphere.isVisible = false;
  68188. }
  68189. };
  68190. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  68191. var impostorObject = impostor.object;
  68192. this._prepareSphere();
  68193. this._sphere.position = origin;
  68194. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  68195. this._sphere._updateBoundingInfo();
  68196. this._sphere.computeWorldMatrix(true);
  68197. return this._sphere.intersectsMesh(impostorObject, true);
  68198. };
  68199. return PhysicsRadialExplosionEvent;
  68200. }());
  68201. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  68202. /***** Gravitational Field *****/
  68203. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  68204. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  68205. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  68206. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  68207. this._physicsHelper = physicsHelper;
  68208. this._scene = scene;
  68209. this._origin = origin;
  68210. this._radius = radius;
  68211. this._strength = strength;
  68212. this._falloff = falloff;
  68213. this._tickCallback = this._tick.bind(this);
  68214. }
  68215. /**
  68216. * Returns the data related to the gravitational field event (sphere).
  68217. * @returns {PhysicsGravitationalFieldEventData}
  68218. */
  68219. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  68220. this._dataFetched = true;
  68221. return {
  68222. sphere: this._sphere,
  68223. };
  68224. };
  68225. /**
  68226. * Enables the gravitational field.
  68227. */
  68228. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  68229. this._tickCallback.call(this);
  68230. this._scene.registerBeforeRender(this._tickCallback);
  68231. };
  68232. /**
  68233. * Disables the gravitational field.
  68234. */
  68235. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  68236. this._scene.unregisterBeforeRender(this._tickCallback);
  68237. };
  68238. /**
  68239. * Disposes the sphere.
  68240. * @param {bolean} force
  68241. */
  68242. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  68243. var _this = this;
  68244. if (force === void 0) { force = true; }
  68245. if (force) {
  68246. this._sphere.dispose();
  68247. }
  68248. else {
  68249. setTimeout(function () {
  68250. if (!_this._dataFetched) {
  68251. _this._sphere.dispose();
  68252. }
  68253. }, 0);
  68254. }
  68255. };
  68256. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  68257. // Since the params won't change, we fetch the event only once
  68258. if (this._sphere) {
  68259. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  68260. }
  68261. else {
  68262. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  68263. if (radialExplosionEvent) {
  68264. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  68265. }
  68266. }
  68267. };
  68268. return PhysicsGravitationalFieldEvent;
  68269. }());
  68270. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  68271. /***** Updraft *****/
  68272. var PhysicsUpdraftEvent = /** @class */ (function () {
  68273. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  68274. this._scene = _scene;
  68275. this._origin = _origin;
  68276. this._radius = _radius;
  68277. this._strength = _strength;
  68278. this._height = _height;
  68279. this._updraftMode = _updraftMode;
  68280. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  68281. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  68282. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  68283. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  68284. this._physicsEngine = this._scene.getPhysicsEngine();
  68285. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  68286. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  68287. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  68288. this._originDirection = this._origin.subtract(this._originTop).normalize();
  68289. }
  68290. this._tickCallback = this._tick.bind(this);
  68291. }
  68292. /**
  68293. * Returns the data related to the updraft event (cylinder).
  68294. * @returns {PhysicsUpdraftEventData}
  68295. */
  68296. PhysicsUpdraftEvent.prototype.getData = function () {
  68297. this._dataFetched = true;
  68298. return {
  68299. cylinder: this._cylinder,
  68300. };
  68301. };
  68302. /**
  68303. * Enables the updraft.
  68304. */
  68305. PhysicsUpdraftEvent.prototype.enable = function () {
  68306. this._tickCallback.call(this);
  68307. this._scene.registerBeforeRender(this._tickCallback);
  68308. };
  68309. /**
  68310. * Disables the cortex.
  68311. */
  68312. PhysicsUpdraftEvent.prototype.disable = function () {
  68313. this._scene.unregisterBeforeRender(this._tickCallback);
  68314. };
  68315. /**
  68316. * Disposes the sphere.
  68317. * @param {bolean} force
  68318. */
  68319. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  68320. var _this = this;
  68321. if (force === void 0) { force = true; }
  68322. if (force) {
  68323. this._cylinder.dispose();
  68324. }
  68325. else {
  68326. setTimeout(function () {
  68327. if (!_this._dataFetched) {
  68328. _this._cylinder.dispose();
  68329. }
  68330. }, 0);
  68331. }
  68332. };
  68333. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  68334. if (impostor.mass === 0) {
  68335. return null;
  68336. }
  68337. if (!this._intersectsWithCylinder(impostor)) {
  68338. return null;
  68339. }
  68340. var impostorObjectCenter = impostor.getObjectCenter();
  68341. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  68342. var direction = this._originDirection;
  68343. }
  68344. else {
  68345. var direction = impostorObjectCenter.subtract(this._originTop);
  68346. }
  68347. var multiplier = this._strength * -1;
  68348. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  68349. return { force: force, contactPoint: impostorObjectCenter };
  68350. };
  68351. PhysicsUpdraftEvent.prototype._tick = function () {
  68352. var _this = this;
  68353. this._physicsEngine.getImpostors().forEach(function (impostor) {
  68354. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  68355. if (!impostorForceAndContactPoint) {
  68356. return;
  68357. }
  68358. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  68359. });
  68360. };
  68361. /*** Helpers ***/
  68362. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  68363. if (!this._cylinder) {
  68364. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  68365. height: this._height,
  68366. diameter: this._radius * 2,
  68367. }, this._scene);
  68368. this._cylinder.isVisible = false;
  68369. }
  68370. };
  68371. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  68372. var impostorObject = impostor.object;
  68373. this._prepareCylinder();
  68374. this._cylinder.position = this._cylinderPosition;
  68375. return this._cylinder.intersectsMesh(impostorObject, true);
  68376. };
  68377. return PhysicsUpdraftEvent;
  68378. }());
  68379. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  68380. /***** Vortex *****/
  68381. var PhysicsVortexEvent = /** @class */ (function () {
  68382. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  68383. this._scene = _scene;
  68384. this._origin = _origin;
  68385. this._radius = _radius;
  68386. this._strength = _strength;
  68387. this._height = _height;
  68388. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  68389. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  68390. this._updraftMultiplier = 0.02;
  68391. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  68392. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  68393. this._physicsEngine = this._scene.getPhysicsEngine();
  68394. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  68395. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  68396. this._tickCallback = this._tick.bind(this);
  68397. }
  68398. /**
  68399. * Returns the data related to the vortex event (cylinder).
  68400. * @returns {PhysicsVortexEventData}
  68401. */
  68402. PhysicsVortexEvent.prototype.getData = function () {
  68403. this._dataFetched = true;
  68404. return {
  68405. cylinder: this._cylinder,
  68406. };
  68407. };
  68408. /**
  68409. * Enables the vortex.
  68410. */
  68411. PhysicsVortexEvent.prototype.enable = function () {
  68412. this._tickCallback.call(this);
  68413. this._scene.registerBeforeRender(this._tickCallback);
  68414. };
  68415. /**
  68416. * Disables the cortex.
  68417. */
  68418. PhysicsVortexEvent.prototype.disable = function () {
  68419. this._scene.unregisterBeforeRender(this._tickCallback);
  68420. };
  68421. /**
  68422. * Disposes the sphere.
  68423. * @param {bolean} force
  68424. */
  68425. PhysicsVortexEvent.prototype.dispose = function (force) {
  68426. var _this = this;
  68427. if (force === void 0) { force = true; }
  68428. if (force) {
  68429. this._cylinder.dispose();
  68430. }
  68431. else {
  68432. setTimeout(function () {
  68433. if (!_this._dataFetched) {
  68434. _this._cylinder.dispose();
  68435. }
  68436. }, 0);
  68437. }
  68438. };
  68439. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  68440. if (impostor.mass === 0) {
  68441. return null;
  68442. }
  68443. if (!this._intersectsWithCylinder(impostor)) {
  68444. return null;
  68445. }
  68446. if (impostor.object.getClassName() !== 'Mesh') {
  68447. return null;
  68448. }
  68449. var impostorObject = impostor.object;
  68450. var impostorObjectCenter = impostor.getObjectCenter();
  68451. 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)
  68452. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  68453. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  68454. var hit = ray.intersectsMesh(impostorObject);
  68455. var contactPoint = hit.pickedPoint;
  68456. if (!contactPoint) {
  68457. return null;
  68458. }
  68459. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  68460. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  68461. var directionToOrigin = contactPoint.normalize();
  68462. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  68463. directionToOrigin = directionToOrigin.negate();
  68464. }
  68465. // TODO: find a more physically based solution
  68466. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  68467. var forceX = directionToOrigin.x * this._strength / 8;
  68468. var forceY = directionToOrigin.y * this._updraftMultiplier;
  68469. var forceZ = directionToOrigin.z * this._strength / 8;
  68470. }
  68471. else {
  68472. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  68473. var forceY = this._originTop.y * this._updraftMultiplier;
  68474. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  68475. }
  68476. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  68477. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  68478. return { force: force, contactPoint: impostorObjectCenter };
  68479. };
  68480. PhysicsVortexEvent.prototype._tick = function () {
  68481. var _this = this;
  68482. this._physicsEngine.getImpostors().forEach(function (impostor) {
  68483. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  68484. if (!impostorForceAndContactPoint) {
  68485. return;
  68486. }
  68487. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  68488. });
  68489. };
  68490. /*** Helpers ***/
  68491. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  68492. if (!this._cylinder) {
  68493. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  68494. height: this._height,
  68495. diameter: this._radius * 2,
  68496. }, this._scene);
  68497. this._cylinder.isVisible = false;
  68498. }
  68499. };
  68500. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  68501. var impostorObject = impostor.object;
  68502. this._prepareCylinder();
  68503. this._cylinder.position = this._cylinderPosition;
  68504. return this._cylinder.intersectsMesh(impostorObject, true);
  68505. };
  68506. return PhysicsVortexEvent;
  68507. }());
  68508. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  68509. /***** Enums *****/
  68510. /**
  68511. * The strenght of the force in correspondence to the distance of the affected object
  68512. */
  68513. var PhysicsRadialImpulseFalloff;
  68514. (function (PhysicsRadialImpulseFalloff) {
  68515. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  68516. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear"; // impulse gets weaker if it's further from the origin
  68517. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  68518. /**
  68519. * The strenght of the force in correspondence to the distance of the affected object
  68520. */
  68521. var PhysicsUpdraftMode;
  68522. (function (PhysicsUpdraftMode) {
  68523. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  68524. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular"; // once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder
  68525. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  68526. })(BABYLON || (BABYLON = {}));
  68527. //# sourceMappingURL=babylon.physicsHelper.js.map
  68528. var BABYLON;
  68529. (function (BABYLON) {
  68530. var CannonJSPlugin = /** @class */ (function () {
  68531. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  68532. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  68533. if (iterations === void 0) { iterations = 10; }
  68534. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  68535. this.name = "CannonJSPlugin";
  68536. this._physicsMaterials = new Array();
  68537. this._fixedTimeStep = 1 / 60;
  68538. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  68539. this.BJSCANNON = typeof CANNON !== 'undefined' ? CANNON : (typeof require !== 'undefined' ? require('cannon') : undefined);
  68540. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  68541. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  68542. this._tmpPosition = BABYLON.Vector3.Zero();
  68543. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  68544. this._tmpUnityRotation = new BABYLON.Quaternion();
  68545. if (!this.isSupported()) {
  68546. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  68547. return;
  68548. }
  68549. this._extendNamespace();
  68550. this.world = new this.BJSCANNON.World();
  68551. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  68552. this.world.solver.iterations = iterations;
  68553. }
  68554. CannonJSPlugin.prototype.setGravity = function (gravity) {
  68555. this.world.gravity.copy(gravity);
  68556. };
  68557. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  68558. this._fixedTimeStep = timeStep;
  68559. };
  68560. CannonJSPlugin.prototype.getTimeStep = function () {
  68561. return this._fixedTimeStep;
  68562. };
  68563. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  68564. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  68565. };
  68566. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  68567. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  68568. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  68569. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  68570. };
  68571. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  68572. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  68573. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  68574. impostor.physicsBody.applyForce(impulse, worldPoint);
  68575. };
  68576. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  68577. //parent-child relationship. Does this impostor has a parent impostor?
  68578. if (impostor.parent) {
  68579. if (impostor.physicsBody) {
  68580. this.removePhysicsBody(impostor);
  68581. //TODO is that needed?
  68582. impostor.forceUpdate();
  68583. }
  68584. return;
  68585. }
  68586. //should a new body be created for this impostor?
  68587. if (impostor.isBodyInitRequired()) {
  68588. var shape = this._createShape(impostor);
  68589. //unregister events, if body is being changed
  68590. var oldBody = impostor.physicsBody;
  68591. if (oldBody) {
  68592. this.removePhysicsBody(impostor);
  68593. }
  68594. //create the body and material
  68595. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  68596. var bodyCreationObject = {
  68597. mass: impostor.getParam("mass"),
  68598. material: material
  68599. };
  68600. // A simple extend, in case native options were used.
  68601. var nativeOptions = impostor.getParam("nativeOptions");
  68602. for (var key in nativeOptions) {
  68603. if (nativeOptions.hasOwnProperty(key)) {
  68604. bodyCreationObject[key] = nativeOptions[key];
  68605. }
  68606. }
  68607. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  68608. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  68609. this.world.addEventListener("preStep", impostor.beforeStep);
  68610. this.world.addEventListener("postStep", impostor.afterStep);
  68611. impostor.physicsBody.addShape(shape);
  68612. this.world.add(impostor.physicsBody);
  68613. //try to keep the body moving in the right direction by taking old properties.
  68614. //Should be tested!
  68615. if (oldBody) {
  68616. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  68617. impostor.physicsBody[param].copy(oldBody[param]);
  68618. });
  68619. }
  68620. this._processChildMeshes(impostor);
  68621. }
  68622. //now update the body's transformation
  68623. this._updatePhysicsBodyTransformation(impostor);
  68624. };
  68625. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  68626. var _this = this;
  68627. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  68628. var currentRotation = mainImpostor.object.rotationQuaternion;
  68629. if (meshChildren.length) {
  68630. var processMesh = function (localPosition, mesh) {
  68631. if (!currentRotation || !mesh.rotationQuaternion) {
  68632. return;
  68633. }
  68634. var childImpostor = mesh.getPhysicsImpostor();
  68635. if (childImpostor) {
  68636. var parent = childImpostor.parent;
  68637. if (parent !== mainImpostor) {
  68638. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  68639. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  68640. if (childImpostor.physicsBody) {
  68641. _this.removePhysicsBody(childImpostor);
  68642. childImpostor.physicsBody = null;
  68643. }
  68644. childImpostor.parent = mainImpostor;
  68645. childImpostor.resetUpdateFlags();
  68646. 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));
  68647. //Add the mass of the children.
  68648. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  68649. }
  68650. }
  68651. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  68652. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  68653. };
  68654. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  68655. }
  68656. };
  68657. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  68658. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  68659. this.world.removeEventListener("preStep", impostor.beforeStep);
  68660. this.world.removeEventListener("postStep", impostor.afterStep);
  68661. this.world.remove(impostor.physicsBody);
  68662. };
  68663. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  68664. var mainBody = impostorJoint.mainImpostor.physicsBody;
  68665. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  68666. if (!mainBody || !connectedBody) {
  68667. return;
  68668. }
  68669. var constraint;
  68670. var jointData = impostorJoint.joint.jointData;
  68671. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  68672. var constraintData = {
  68673. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  68674. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  68675. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  68676. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  68677. maxForce: jointData.nativeParams.maxForce,
  68678. collideConnected: !!jointData.collision
  68679. };
  68680. switch (impostorJoint.joint.type) {
  68681. case BABYLON.PhysicsJoint.HingeJoint:
  68682. case BABYLON.PhysicsJoint.Hinge2Joint:
  68683. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  68684. break;
  68685. case BABYLON.PhysicsJoint.DistanceJoint:
  68686. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  68687. break;
  68688. case BABYLON.PhysicsJoint.SpringJoint:
  68689. var springData = jointData;
  68690. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  68691. restLength: springData.length,
  68692. stiffness: springData.stiffness,
  68693. damping: springData.damping,
  68694. localAnchorA: constraintData.pivotA,
  68695. localAnchorB: constraintData.pivotB
  68696. });
  68697. break;
  68698. case BABYLON.PhysicsJoint.LockJoint:
  68699. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  68700. break;
  68701. case BABYLON.PhysicsJoint.PointToPointJoint:
  68702. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  68703. default:
  68704. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  68705. break;
  68706. }
  68707. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  68708. constraint.collideConnected = !!jointData.collision;
  68709. impostorJoint.joint.physicsJoint = constraint;
  68710. //don't add spring as constraint, as it is not one.
  68711. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  68712. this.world.addConstraint(constraint);
  68713. }
  68714. else {
  68715. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  68716. constraint.applyForce();
  68717. });
  68718. }
  68719. };
  68720. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  68721. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  68722. };
  68723. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  68724. var index;
  68725. var mat;
  68726. for (index = 0; index < this._physicsMaterials.length; index++) {
  68727. mat = this._physicsMaterials[index];
  68728. if (mat.friction === friction && mat.restitution === restitution) {
  68729. return mat;
  68730. }
  68731. }
  68732. var currentMat = new this.BJSCANNON.Material(name);
  68733. currentMat.friction = friction;
  68734. currentMat.restitution = restitution;
  68735. this._physicsMaterials.push(currentMat);
  68736. return currentMat;
  68737. };
  68738. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  68739. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  68740. };
  68741. CannonJSPlugin.prototype._createShape = function (impostor) {
  68742. var object = impostor.object;
  68743. var returnValue;
  68744. var extendSize = impostor.getObjectExtendSize();
  68745. switch (impostor.type) {
  68746. case BABYLON.PhysicsImpostor.SphereImpostor:
  68747. var radiusX = extendSize.x;
  68748. var radiusY = extendSize.y;
  68749. var radiusZ = extendSize.z;
  68750. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  68751. break;
  68752. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  68753. case BABYLON.PhysicsImpostor.CylinderImpostor:
  68754. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  68755. break;
  68756. case BABYLON.PhysicsImpostor.BoxImpostor:
  68757. var box = extendSize.scale(0.5);
  68758. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  68759. break;
  68760. case BABYLON.PhysicsImpostor.PlaneImpostor:
  68761. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  68762. returnValue = new this.BJSCANNON.Plane();
  68763. break;
  68764. case BABYLON.PhysicsImpostor.MeshImpostor:
  68765. // should transform the vertex data to world coordinates!!
  68766. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  68767. var rawFaces = object.getIndices ? object.getIndices() : [];
  68768. if (!rawVerts)
  68769. return;
  68770. // get only scale! so the object could transform correctly.
  68771. var oldPosition = object.position.clone();
  68772. var oldRotation = object.rotation && object.rotation.clone();
  68773. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  68774. object.position.copyFromFloats(0, 0, 0);
  68775. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  68776. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  68777. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  68778. var transform = object.computeWorldMatrix(true);
  68779. // convert rawVerts to object space
  68780. var temp = new Array();
  68781. var index;
  68782. for (index = 0; index < rawVerts.length; index += 3) {
  68783. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  68784. }
  68785. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  68786. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  68787. //now set back the transformation!
  68788. object.position.copyFrom(oldPosition);
  68789. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  68790. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  68791. break;
  68792. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  68793. var oldPosition2 = object.position.clone();
  68794. var oldRotation2 = object.rotation && object.rotation.clone();
  68795. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  68796. object.position.copyFromFloats(0, 0, 0);
  68797. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  68798. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  68799. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  68800. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  68801. returnValue = this._createHeightmap(object);
  68802. object.position.copyFrom(oldPosition2);
  68803. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  68804. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  68805. object.computeWorldMatrix(true);
  68806. break;
  68807. case BABYLON.PhysicsImpostor.ParticleImpostor:
  68808. returnValue = new this.BJSCANNON.Particle();
  68809. break;
  68810. }
  68811. return returnValue;
  68812. };
  68813. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  68814. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  68815. var transform = object.computeWorldMatrix(true);
  68816. // convert rawVerts to object space
  68817. var temp = new Array();
  68818. var index;
  68819. for (index = 0; index < pos.length; index += 3) {
  68820. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  68821. }
  68822. pos = temp;
  68823. var matrix = new Array();
  68824. //For now pointDepth will not be used and will be automatically calculated.
  68825. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  68826. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  68827. var boundingInfo = object.getBoundingInfo();
  68828. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  68829. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  68830. var elementSize = dim * 2 / arraySize;
  68831. for (var i = 0; i < pos.length; i = i + 3) {
  68832. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  68833. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  68834. var y = -pos[i + 2] + minY;
  68835. if (!matrix[x]) {
  68836. matrix[x] = [];
  68837. }
  68838. if (!matrix[x][z]) {
  68839. matrix[x][z] = y;
  68840. }
  68841. matrix[x][z] = Math.max(y, matrix[x][z]);
  68842. }
  68843. for (var x = 0; x <= arraySize; ++x) {
  68844. if (!matrix[x]) {
  68845. var loc = 1;
  68846. while (!matrix[(x + loc) % arraySize]) {
  68847. loc++;
  68848. }
  68849. matrix[x] = matrix[(x + loc) % arraySize].slice();
  68850. //console.log("missing x", x);
  68851. }
  68852. for (var z = 0; z <= arraySize; ++z) {
  68853. if (!matrix[x][z]) {
  68854. var loc = 1;
  68855. var newValue;
  68856. while (newValue === undefined) {
  68857. newValue = matrix[x][(z + loc++) % arraySize];
  68858. }
  68859. matrix[x][z] = newValue;
  68860. }
  68861. }
  68862. }
  68863. var shape = new this.BJSCANNON.Heightfield(matrix, {
  68864. elementSize: elementSize
  68865. });
  68866. //For future reference, needed for body transformation
  68867. shape.minY = minY;
  68868. return shape;
  68869. };
  68870. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  68871. var object = impostor.object;
  68872. //make sure it is updated...
  68873. object.computeWorldMatrix && object.computeWorldMatrix(true);
  68874. // The delta between the mesh position and the mesh bounding box center
  68875. var bInfo = object.getBoundingInfo();
  68876. if (!bInfo)
  68877. return;
  68878. var center = impostor.getObjectCenter();
  68879. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  68880. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  68881. this._tmpPosition.copyFrom(center);
  68882. var quaternion = object.rotationQuaternion;
  68883. if (!quaternion) {
  68884. return;
  68885. }
  68886. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  68887. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  68888. //-90 DEG in X, precalculated
  68889. quaternion = quaternion.multiply(this._minus90X);
  68890. //Invert! (Precalculated, 90 deg in X)
  68891. //No need to clone. this will never change.
  68892. impostor.setDeltaRotation(this._plus90X);
  68893. }
  68894. //If it is a heightfield, if should be centered.
  68895. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  68896. var mesh = object;
  68897. var boundingInfo = mesh.getBoundingInfo();
  68898. //calculate the correct body position:
  68899. var rotationQuaternion = mesh.rotationQuaternion;
  68900. mesh.rotationQuaternion = this._tmpUnityRotation;
  68901. mesh.computeWorldMatrix(true);
  68902. //get original center with no rotation
  68903. var c = center.clone();
  68904. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  68905. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  68906. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  68907. mesh.setPivotMatrix(p);
  68908. mesh.computeWorldMatrix(true);
  68909. //calculate the translation
  68910. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  68911. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  68912. //add it inverted to the delta
  68913. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  68914. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  68915. //rotation is back
  68916. mesh.rotationQuaternion = rotationQuaternion;
  68917. mesh.setPivotMatrix(oldPivot);
  68918. mesh.computeWorldMatrix(true);
  68919. }
  68920. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  68921. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  68922. //this._tmpPosition.copyFrom(object.position);
  68923. }
  68924. impostor.setDeltaPosition(this._tmpDeltaPosition);
  68925. //Now update the impostor object
  68926. impostor.physicsBody.position.copy(this._tmpPosition);
  68927. impostor.physicsBody.quaternion.copy(quaternion);
  68928. };
  68929. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  68930. impostor.object.position.copyFrom(impostor.physicsBody.position);
  68931. if (impostor.object.rotationQuaternion) {
  68932. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  68933. }
  68934. };
  68935. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  68936. impostor.physicsBody.position.copy(newPosition);
  68937. impostor.physicsBody.quaternion.copy(newRotation);
  68938. };
  68939. CannonJSPlugin.prototype.isSupported = function () {
  68940. return this.BJSCANNON !== undefined;
  68941. };
  68942. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  68943. impostor.physicsBody.velocity.copy(velocity);
  68944. };
  68945. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  68946. impostor.physicsBody.angularVelocity.copy(velocity);
  68947. };
  68948. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  68949. var v = impostor.physicsBody.velocity;
  68950. if (!v) {
  68951. return null;
  68952. }
  68953. return new BABYLON.Vector3(v.x, v.y, v.z);
  68954. };
  68955. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  68956. var v = impostor.physicsBody.angularVelocity;
  68957. if (!v) {
  68958. return null;
  68959. }
  68960. return new BABYLON.Vector3(v.x, v.y, v.z);
  68961. };
  68962. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  68963. impostor.physicsBody.mass = mass;
  68964. impostor.physicsBody.updateMassProperties();
  68965. };
  68966. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  68967. return impostor.physicsBody.mass;
  68968. };
  68969. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  68970. return impostor.physicsBody.material.friction;
  68971. };
  68972. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  68973. impostor.physicsBody.material.friction = friction;
  68974. };
  68975. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  68976. return impostor.physicsBody.material.restitution;
  68977. };
  68978. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  68979. impostor.physicsBody.material.restitution = restitution;
  68980. };
  68981. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  68982. impostor.physicsBody.sleep();
  68983. };
  68984. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  68985. impostor.physicsBody.wakeUp();
  68986. };
  68987. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  68988. joint.physicsJoint.distance = maxDistance;
  68989. };
  68990. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  68991. // if (!motorIndex) {
  68992. // joint.physicsJoint.enableMotor();
  68993. // }
  68994. // }
  68995. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  68996. // if (!motorIndex) {
  68997. // joint.physicsJoint.disableMotor();
  68998. // }
  68999. // }
  69000. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  69001. if (!motorIndex) {
  69002. joint.physicsJoint.enableMotor();
  69003. joint.physicsJoint.setMotorSpeed(speed);
  69004. if (maxForce) {
  69005. this.setLimit(joint, maxForce);
  69006. }
  69007. }
  69008. };
  69009. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  69010. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  69011. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  69012. };
  69013. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  69014. var body = impostor.physicsBody;
  69015. mesh.position.x = body.position.x;
  69016. mesh.position.y = body.position.y;
  69017. mesh.position.z = body.position.z;
  69018. if (mesh.rotationQuaternion) {
  69019. mesh.rotationQuaternion.x = body.quaternion.x;
  69020. mesh.rotationQuaternion.y = body.quaternion.y;
  69021. mesh.rotationQuaternion.z = body.quaternion.z;
  69022. mesh.rotationQuaternion.w = body.quaternion.w;
  69023. }
  69024. };
  69025. CannonJSPlugin.prototype.getRadius = function (impostor) {
  69026. var shape = impostor.physicsBody.shapes[0];
  69027. return shape.boundingSphereRadius;
  69028. };
  69029. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  69030. var shape = impostor.physicsBody.shapes[0];
  69031. result.x = shape.halfExtents.x * 2;
  69032. result.y = shape.halfExtents.y * 2;
  69033. result.z = shape.halfExtents.z * 2;
  69034. };
  69035. CannonJSPlugin.prototype.dispose = function () {
  69036. };
  69037. CannonJSPlugin.prototype._extendNamespace = function () {
  69038. //this will force cannon to execute at least one step when using interpolation
  69039. var step_tmp1 = new this.BJSCANNON.Vec3();
  69040. var Engine = this.BJSCANNON;
  69041. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  69042. maxSubSteps = maxSubSteps || 10;
  69043. timeSinceLastCalled = timeSinceLastCalled || 0;
  69044. if (timeSinceLastCalled === 0) {
  69045. this.internalStep(dt);
  69046. this.time += dt;
  69047. }
  69048. else {
  69049. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  69050. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  69051. var t0 = performance.now();
  69052. for (var i = 0; i !== internalSteps; i++) {
  69053. this.internalStep(dt);
  69054. if (performance.now() - t0 > dt * 1000) {
  69055. break;
  69056. }
  69057. }
  69058. this.time += timeSinceLastCalled;
  69059. var h = this.time % dt;
  69060. var h_div_dt = h / dt;
  69061. var interpvelo = step_tmp1;
  69062. var bodies = this.bodies;
  69063. for (var j = 0; j !== bodies.length; j++) {
  69064. var b = bodies[j];
  69065. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  69066. b.position.vsub(b.previousPosition, interpvelo);
  69067. interpvelo.scale(h_div_dt, interpvelo);
  69068. b.position.vadd(interpvelo, b.interpolatedPosition);
  69069. }
  69070. else {
  69071. b.interpolatedPosition.copy(b.position);
  69072. b.interpolatedQuaternion.copy(b.quaternion);
  69073. }
  69074. }
  69075. }
  69076. };
  69077. };
  69078. return CannonJSPlugin;
  69079. }());
  69080. BABYLON.CannonJSPlugin = CannonJSPlugin;
  69081. })(BABYLON || (BABYLON = {}));
  69082. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  69083. var BABYLON;
  69084. (function (BABYLON) {
  69085. var OimoJSPlugin = /** @class */ (function () {
  69086. function OimoJSPlugin(iterations) {
  69087. this.name = "OimoJSPlugin";
  69088. this._tmpImpostorsArray = [];
  69089. this._tmpPositionVector = BABYLON.Vector3.Zero();
  69090. this.BJSOIMO = typeof OIMO !== 'undefined' ? OIMO : (typeof require !== 'undefined' ? require('./Oimo') : undefined);
  69091. this.world = new this.BJSOIMO.World(1 / 60, 2, iterations, true);
  69092. this.world.worldscale(1);
  69093. this.world.clear();
  69094. //making sure no stats are calculated
  69095. this.world.isNoStat = true;
  69096. }
  69097. OimoJSPlugin.prototype.setGravity = function (gravity) {
  69098. this.world.gravity.copy(gravity);
  69099. };
  69100. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  69101. this.world.timeStep = timeStep;
  69102. };
  69103. OimoJSPlugin.prototype.getTimeStep = function () {
  69104. return this.world.timeStep;
  69105. };
  69106. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  69107. var _this = this;
  69108. impostors.forEach(function (impostor) {
  69109. impostor.beforeStep();
  69110. });
  69111. this.world.step();
  69112. impostors.forEach(function (impostor) {
  69113. impostor.afterStep();
  69114. //update the ordered impostors array
  69115. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  69116. });
  69117. //check for collisions
  69118. var contact = this.world.contacts;
  69119. while (contact !== null) {
  69120. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  69121. contact = contact.next;
  69122. continue;
  69123. }
  69124. //is this body colliding with any other? get the impostor
  69125. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  69126. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  69127. if (!mainImpostor || !collidingImpostor) {
  69128. contact = contact.next;
  69129. continue;
  69130. }
  69131. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  69132. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  69133. contact = contact.next;
  69134. }
  69135. };
  69136. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  69137. var mass = impostor.physicsBody.massInfo.mass;
  69138. impostor.physicsBody.applyImpulse(contactPoint.scale(this.BJSOIMO.INV_SCALE), force.scale(this.BJSOIMO.INV_SCALE * mass));
  69139. };
  69140. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  69141. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  69142. this.applyImpulse(impostor, force, contactPoint);
  69143. };
  69144. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  69145. var _this = this;
  69146. //parent-child relationship. Does this impostor has a parent impostor?
  69147. if (impostor.parent) {
  69148. if (impostor.physicsBody) {
  69149. this.removePhysicsBody(impostor);
  69150. //TODO is that needed?
  69151. impostor.forceUpdate();
  69152. }
  69153. return;
  69154. }
  69155. if (impostor.isBodyInitRequired()) {
  69156. var bodyConfig = {
  69157. name: impostor.uniqueId,
  69158. //Oimo must have mass, also for static objects.
  69159. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  69160. size: [],
  69161. type: [],
  69162. pos: [],
  69163. rot: [],
  69164. move: impostor.getParam("mass") !== 0,
  69165. //Supporting older versions of Oimo
  69166. world: this.world
  69167. };
  69168. var impostors = [impostor];
  69169. var addToArray = function (parent) {
  69170. if (!parent.getChildMeshes)
  69171. return;
  69172. parent.getChildMeshes().forEach(function (m) {
  69173. if (m.physicsImpostor) {
  69174. impostors.push(m.physicsImpostor);
  69175. //m.physicsImpostor._init();
  69176. }
  69177. });
  69178. };
  69179. addToArray(impostor.object);
  69180. var checkWithEpsilon_1 = function (value) {
  69181. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  69182. };
  69183. impostors.forEach(function (i) {
  69184. if (!impostor.object.rotationQuaternion) {
  69185. return;
  69186. }
  69187. //get the correct bounding box
  69188. var oldQuaternion = i.object.rotationQuaternion;
  69189. var rot = new _this.BJSOIMO.Euler().setFromQuaternion({
  69190. x: impostor.object.rotationQuaternion.x,
  69191. y: impostor.object.rotationQuaternion.y,
  69192. z: impostor.object.rotationQuaternion.z,
  69193. s: impostor.object.rotationQuaternion.w
  69194. });
  69195. var extendSize = i.getObjectExtendSize();
  69196. if (i === impostor) {
  69197. var center = impostor.getObjectCenter();
  69198. impostor.object.position.subtractToRef(center, _this._tmpPositionVector);
  69199. //Can also use Array.prototype.push.apply
  69200. bodyConfig.pos.push(center.x);
  69201. bodyConfig.pos.push(center.y);
  69202. bodyConfig.pos.push(center.z);
  69203. //tmp solution
  69204. bodyConfig.rot.push(rot.x / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  69205. bodyConfig.rot.push(rot.y / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  69206. bodyConfig.rot.push(rot.z / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  69207. }
  69208. else {
  69209. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  69210. bodyConfig.pos.push(localPosition.x);
  69211. bodyConfig.pos.push(localPosition.y);
  69212. bodyConfig.pos.push(localPosition.z);
  69213. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  69214. bodyConfig.rot.push(0);
  69215. bodyConfig.rot.push(0);
  69216. bodyConfig.rot.push(0);
  69217. }
  69218. // register mesh
  69219. switch (i.type) {
  69220. case BABYLON.PhysicsImpostor.ParticleImpostor:
  69221. BABYLON.Tools.Warn("No Particle support in this.BJSOIMO.js. using SphereImpostor instead");
  69222. case BABYLON.PhysicsImpostor.SphereImpostor:
  69223. var radiusX = extendSize.x;
  69224. var radiusY = extendSize.y;
  69225. var radiusZ = extendSize.z;
  69226. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  69227. bodyConfig.type.push('sphere');
  69228. //due to the way oimo works with compounds, add 3 times
  69229. bodyConfig.size.push(size);
  69230. bodyConfig.size.push(size);
  69231. bodyConfig.size.push(size);
  69232. break;
  69233. case BABYLON.PhysicsImpostor.CylinderImpostor:
  69234. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  69235. var sizeY = checkWithEpsilon_1(extendSize.y);
  69236. bodyConfig.type.push('cylinder');
  69237. bodyConfig.size.push(sizeX);
  69238. bodyConfig.size.push(sizeY);
  69239. //due to the way oimo works with compounds, add one more value.
  69240. bodyConfig.size.push(sizeY);
  69241. break;
  69242. case BABYLON.PhysicsImpostor.PlaneImpostor:
  69243. case BABYLON.PhysicsImpostor.BoxImpostor:
  69244. default:
  69245. var sizeX = checkWithEpsilon_1(extendSize.x);
  69246. var sizeY = checkWithEpsilon_1(extendSize.y);
  69247. var sizeZ = checkWithEpsilon_1(extendSize.z);
  69248. bodyConfig.type.push('box');
  69249. bodyConfig.size.push(sizeX);
  69250. bodyConfig.size.push(sizeY);
  69251. bodyConfig.size.push(sizeZ);
  69252. break;
  69253. }
  69254. //actually not needed, but hey...
  69255. i.object.rotationQuaternion = oldQuaternion;
  69256. });
  69257. impostor.physicsBody = new this.BJSOIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  69258. }
  69259. else {
  69260. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  69261. }
  69262. impostor.setDeltaPosition(this._tmpPositionVector);
  69263. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  69264. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  69265. };
  69266. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  69267. //impostor.physicsBody.dispose();
  69268. //Same as : (older oimo versions)
  69269. this.world.removeRigidBody(impostor.physicsBody);
  69270. };
  69271. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  69272. var mainBody = impostorJoint.mainImpostor.physicsBody;
  69273. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  69274. if (!mainBody || !connectedBody) {
  69275. return;
  69276. }
  69277. var jointData = impostorJoint.joint.jointData;
  69278. var options = jointData.nativeParams || {};
  69279. var type;
  69280. var nativeJointData = {
  69281. body1: mainBody,
  69282. body2: connectedBody,
  69283. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  69284. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  69285. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  69286. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  69287. min: options.min,
  69288. max: options.max,
  69289. collision: options.collision || jointData.collision,
  69290. spring: options.spring,
  69291. //supporting older version of Oimo
  69292. world: this.world
  69293. };
  69294. switch (impostorJoint.joint.type) {
  69295. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  69296. type = "jointBall";
  69297. break;
  69298. case BABYLON.PhysicsJoint.SpringJoint:
  69299. BABYLON.Tools.Warn("this.BJSOIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  69300. var springData = jointData;
  69301. nativeJointData.min = springData.length || nativeJointData.min;
  69302. //Max should also be set, just make sure it is at least min
  69303. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  69304. case BABYLON.PhysicsJoint.DistanceJoint:
  69305. type = "jointDistance";
  69306. nativeJointData.max = jointData.maxDistance;
  69307. break;
  69308. case BABYLON.PhysicsJoint.PrismaticJoint:
  69309. type = "jointPrisme";
  69310. break;
  69311. case BABYLON.PhysicsJoint.SliderJoint:
  69312. type = "jointSlide";
  69313. break;
  69314. case BABYLON.PhysicsJoint.WheelJoint:
  69315. type = "jointWheel";
  69316. break;
  69317. case BABYLON.PhysicsJoint.HingeJoint:
  69318. default:
  69319. type = "jointHinge";
  69320. break;
  69321. }
  69322. nativeJointData.type = type;
  69323. impostorJoint.joint.physicsJoint = new this.BJSOIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  69324. };
  69325. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  69326. //Bug in Oimo prevents us from disposing a joint in the playground
  69327. //joint.joint.physicsJoint.dispose();
  69328. //So we will bruteforce it!
  69329. try {
  69330. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  69331. }
  69332. catch (e) {
  69333. BABYLON.Tools.Warn(e);
  69334. }
  69335. };
  69336. OimoJSPlugin.prototype.isSupported = function () {
  69337. return this.BJSOIMO !== undefined;
  69338. };
  69339. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  69340. if (!impostor.physicsBody.sleeping) {
  69341. //TODO check that
  69342. if (impostor.physicsBody.shapes.next) {
  69343. var parentShape = this._getLastShape(impostor.physicsBody);
  69344. impostor.object.position.x = parentShape.position.x * this.BJSOIMO.WORLD_SCALE;
  69345. impostor.object.position.y = parentShape.position.y * this.BJSOIMO.WORLD_SCALE;
  69346. impostor.object.position.z = parentShape.position.z * this.BJSOIMO.WORLD_SCALE;
  69347. }
  69348. else {
  69349. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  69350. }
  69351. if (impostor.object.rotationQuaternion) {
  69352. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  69353. impostor.object.rotationQuaternion.normalize();
  69354. }
  69355. }
  69356. };
  69357. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  69358. var body = impostor.physicsBody;
  69359. body.position.init(newPosition.x * this.BJSOIMO.INV_SCALE, newPosition.y * this.BJSOIMO.INV_SCALE, newPosition.z * this.BJSOIMO.INV_SCALE);
  69360. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  69361. body.syncShapes();
  69362. body.awake();
  69363. };
  69364. OimoJSPlugin.prototype._getLastShape = function (body) {
  69365. var lastShape = body.shapes;
  69366. while (lastShape.next) {
  69367. lastShape = lastShape.next;
  69368. }
  69369. return lastShape;
  69370. };
  69371. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  69372. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  69373. };
  69374. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  69375. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  69376. };
  69377. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  69378. var v = impostor.physicsBody.linearVelocity;
  69379. if (!v) {
  69380. return null;
  69381. }
  69382. return new BABYLON.Vector3(v.x, v.y, v.z);
  69383. };
  69384. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  69385. var v = impostor.physicsBody.angularVelocity;
  69386. if (!v) {
  69387. return null;
  69388. }
  69389. return new BABYLON.Vector3(v.x, v.y, v.z);
  69390. };
  69391. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  69392. var staticBody = mass === 0;
  69393. //this will actually set the body's density and not its mass.
  69394. //But this is how oimo treats the mass variable.
  69395. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  69396. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  69397. };
  69398. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  69399. return impostor.physicsBody.shapes.density;
  69400. };
  69401. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  69402. return impostor.physicsBody.shapes.friction;
  69403. };
  69404. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  69405. impostor.physicsBody.shapes.friction = friction;
  69406. };
  69407. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  69408. return impostor.physicsBody.shapes.restitution;
  69409. };
  69410. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  69411. impostor.physicsBody.shapes.restitution = restitution;
  69412. };
  69413. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  69414. impostor.physicsBody.sleep();
  69415. };
  69416. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  69417. impostor.physicsBody.awake();
  69418. };
  69419. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  69420. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  69421. if (minDistance !== void 0) {
  69422. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  69423. }
  69424. };
  69425. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  69426. //TODO separate rotational and transational motors.
  69427. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  69428. if (motor) {
  69429. motor.setMotor(speed, maxForce);
  69430. }
  69431. };
  69432. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  69433. //TODO separate rotational and transational motors.
  69434. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  69435. if (motor) {
  69436. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  69437. }
  69438. };
  69439. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  69440. var body = impostor.physicsBody;
  69441. mesh.position.x = body.position.x;
  69442. mesh.position.y = body.position.y;
  69443. mesh.position.z = body.position.z;
  69444. if (mesh.rotationQuaternion) {
  69445. mesh.rotationQuaternion.x = body.orientation.x;
  69446. mesh.rotationQuaternion.y = body.orientation.y;
  69447. mesh.rotationQuaternion.z = body.orientation.z;
  69448. mesh.rotationQuaternion.w = body.orientation.s;
  69449. }
  69450. };
  69451. OimoJSPlugin.prototype.getRadius = function (impostor) {
  69452. return impostor.physicsBody.shapes.radius;
  69453. };
  69454. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  69455. var shape = impostor.physicsBody.shapes;
  69456. result.x = shape.halfWidth * 2;
  69457. result.y = shape.halfHeight * 2;
  69458. result.z = shape.halfDepth * 2;
  69459. };
  69460. OimoJSPlugin.prototype.dispose = function () {
  69461. this.world.clear();
  69462. };
  69463. return OimoJSPlugin;
  69464. }());
  69465. BABYLON.OimoJSPlugin = OimoJSPlugin;
  69466. })(BABYLON || (BABYLON = {}));
  69467. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  69468. var BABYLON;
  69469. (function (BABYLON) {
  69470. var Internals;
  69471. (function (Internals) {
  69472. /*
  69473. * Based on jsTGALoader - Javascript loader for TGA file
  69474. * By Vincent Thibault
  69475. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  69476. */
  69477. var TGATools = /** @class */ (function () {
  69478. function TGATools() {
  69479. }
  69480. TGATools.GetTGAHeader = function (data) {
  69481. var offset = 0;
  69482. var header = {
  69483. id_length: data[offset++],
  69484. colormap_type: data[offset++],
  69485. image_type: data[offset++],
  69486. colormap_index: data[offset++] | data[offset++] << 8,
  69487. colormap_length: data[offset++] | data[offset++] << 8,
  69488. colormap_size: data[offset++],
  69489. origin: [
  69490. data[offset++] | data[offset++] << 8,
  69491. data[offset++] | data[offset++] << 8
  69492. ],
  69493. width: data[offset++] | data[offset++] << 8,
  69494. height: data[offset++] | data[offset++] << 8,
  69495. pixel_size: data[offset++],
  69496. flags: data[offset++]
  69497. };
  69498. return header;
  69499. };
  69500. TGATools.UploadContent = function (gl, data) {
  69501. // Not enough data to contain header ?
  69502. if (data.length < 19) {
  69503. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  69504. return;
  69505. }
  69506. // Read Header
  69507. var offset = 18;
  69508. var header = TGATools.GetTGAHeader(data);
  69509. // Assume it's a valid Targa file.
  69510. if (header.id_length + offset > data.length) {
  69511. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  69512. return;
  69513. }
  69514. // Skip not needed data
  69515. offset += header.id_length;
  69516. var use_rle = false;
  69517. var use_pal = false;
  69518. var use_grey = false;
  69519. // Get some informations.
  69520. switch (header.image_type) {
  69521. case TGATools._TYPE_RLE_INDEXED:
  69522. use_rle = true;
  69523. case TGATools._TYPE_INDEXED:
  69524. use_pal = true;
  69525. break;
  69526. case TGATools._TYPE_RLE_RGB:
  69527. use_rle = true;
  69528. case TGATools._TYPE_RGB:
  69529. // use_rgb = true;
  69530. break;
  69531. case TGATools._TYPE_RLE_GREY:
  69532. use_rle = true;
  69533. case TGATools._TYPE_GREY:
  69534. use_grey = true;
  69535. break;
  69536. }
  69537. var pixel_data;
  69538. // var numAlphaBits = header.flags & 0xf;
  69539. var pixel_size = header.pixel_size >> 3;
  69540. var pixel_total = header.width * header.height * pixel_size;
  69541. // Read palettes
  69542. var palettes;
  69543. if (use_pal) {
  69544. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  69545. }
  69546. // Read LRE
  69547. if (use_rle) {
  69548. pixel_data = new Uint8Array(pixel_total);
  69549. var c, count, i;
  69550. var localOffset = 0;
  69551. var pixels = new Uint8Array(pixel_size);
  69552. while (offset < pixel_total && localOffset < pixel_total) {
  69553. c = data[offset++];
  69554. count = (c & 0x7f) + 1;
  69555. // RLE pixels
  69556. if (c & 0x80) {
  69557. // Bind pixel tmp array
  69558. for (i = 0; i < pixel_size; ++i) {
  69559. pixels[i] = data[offset++];
  69560. }
  69561. // Copy pixel array
  69562. for (i = 0; i < count; ++i) {
  69563. pixel_data.set(pixels, localOffset + i * pixel_size);
  69564. }
  69565. localOffset += pixel_size * count;
  69566. }
  69567. else {
  69568. count *= pixel_size;
  69569. for (i = 0; i < count; ++i) {
  69570. pixel_data[localOffset + i] = data[offset++];
  69571. }
  69572. localOffset += count;
  69573. }
  69574. }
  69575. }
  69576. else {
  69577. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  69578. }
  69579. // Load to texture
  69580. var x_start, y_start, x_step, y_step, y_end, x_end;
  69581. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  69582. default:
  69583. case TGATools._ORIGIN_UL:
  69584. x_start = 0;
  69585. x_step = 1;
  69586. x_end = header.width;
  69587. y_start = 0;
  69588. y_step = 1;
  69589. y_end = header.height;
  69590. break;
  69591. case TGATools._ORIGIN_BL:
  69592. x_start = 0;
  69593. x_step = 1;
  69594. x_end = header.width;
  69595. y_start = header.height - 1;
  69596. y_step = -1;
  69597. y_end = -1;
  69598. break;
  69599. case TGATools._ORIGIN_UR:
  69600. x_start = header.width - 1;
  69601. x_step = -1;
  69602. x_end = -1;
  69603. y_start = 0;
  69604. y_step = 1;
  69605. y_end = header.height;
  69606. break;
  69607. case TGATools._ORIGIN_BR:
  69608. x_start = header.width - 1;
  69609. x_step = -1;
  69610. x_end = -1;
  69611. y_start = header.height - 1;
  69612. y_step = -1;
  69613. y_end = -1;
  69614. break;
  69615. }
  69616. // Load the specify method
  69617. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  69618. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  69619. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  69620. };
  69621. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  69622. var image = pixel_data, colormap = palettes;
  69623. var width = header.width, height = header.height;
  69624. var color, i = 0, x, y;
  69625. var imageData = new Uint8Array(width * height * 4);
  69626. for (y = y_start; y !== y_end; y += y_step) {
  69627. for (x = x_start; x !== x_end; x += x_step, i++) {
  69628. color = image[i];
  69629. imageData[(x + width * y) * 4 + 3] = 255;
  69630. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  69631. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  69632. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  69633. }
  69634. }
  69635. return imageData;
  69636. };
  69637. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  69638. var image = pixel_data;
  69639. var width = header.width, height = header.height;
  69640. var color, i = 0, x, y;
  69641. var imageData = new Uint8Array(width * height * 4);
  69642. for (y = y_start; y !== y_end; y += y_step) {
  69643. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  69644. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  69645. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  69646. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  69647. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  69648. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  69649. }
  69650. }
  69651. return imageData;
  69652. };
  69653. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  69654. var image = pixel_data;
  69655. var width = header.width, height = header.height;
  69656. var i = 0, x, y;
  69657. var imageData = new Uint8Array(width * height * 4);
  69658. for (y = y_start; y !== y_end; y += y_step) {
  69659. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  69660. imageData[(x + width * y) * 4 + 3] = 255;
  69661. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  69662. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  69663. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  69664. }
  69665. }
  69666. return imageData;
  69667. };
  69668. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  69669. var image = pixel_data;
  69670. var width = header.width, height = header.height;
  69671. var i = 0, x, y;
  69672. var imageData = new Uint8Array(width * height * 4);
  69673. for (y = y_start; y !== y_end; y += y_step) {
  69674. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  69675. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  69676. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  69677. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  69678. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  69679. }
  69680. }
  69681. return imageData;
  69682. };
  69683. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  69684. var image = pixel_data;
  69685. var width = header.width, height = header.height;
  69686. var color, i = 0, x, y;
  69687. var imageData = new Uint8Array(width * height * 4);
  69688. for (y = y_start; y !== y_end; y += y_step) {
  69689. for (x = x_start; x !== x_end; x += x_step, i++) {
  69690. color = image[i];
  69691. imageData[(x + width * y) * 4 + 0] = color;
  69692. imageData[(x + width * y) * 4 + 1] = color;
  69693. imageData[(x + width * y) * 4 + 2] = color;
  69694. imageData[(x + width * y) * 4 + 3] = 255;
  69695. }
  69696. }
  69697. return imageData;
  69698. };
  69699. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  69700. var image = pixel_data;
  69701. var width = header.width, height = header.height;
  69702. var i = 0, x, y;
  69703. var imageData = new Uint8Array(width * height * 4);
  69704. for (y = y_start; y !== y_end; y += y_step) {
  69705. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  69706. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  69707. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  69708. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  69709. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  69710. }
  69711. }
  69712. return imageData;
  69713. };
  69714. //private static _TYPE_NO_DATA = 0;
  69715. TGATools._TYPE_INDEXED = 1;
  69716. TGATools._TYPE_RGB = 2;
  69717. TGATools._TYPE_GREY = 3;
  69718. TGATools._TYPE_RLE_INDEXED = 9;
  69719. TGATools._TYPE_RLE_RGB = 10;
  69720. TGATools._TYPE_RLE_GREY = 11;
  69721. TGATools._ORIGIN_MASK = 0x30;
  69722. TGATools._ORIGIN_SHIFT = 0x04;
  69723. TGATools._ORIGIN_BL = 0x00;
  69724. TGATools._ORIGIN_BR = 0x01;
  69725. TGATools._ORIGIN_UL = 0x02;
  69726. TGATools._ORIGIN_UR = 0x03;
  69727. return TGATools;
  69728. }());
  69729. Internals.TGATools = TGATools;
  69730. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  69731. })(BABYLON || (BABYLON = {}));
  69732. //# sourceMappingURL=babylon.tga.js.map
  69733. var BABYLON;
  69734. (function (BABYLON) {
  69735. var Internals;
  69736. (function (Internals) {
  69737. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  69738. // All values and structures referenced from:
  69739. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  69740. var DDS_MAGIC = 0x20534444;
  69741. var
  69742. //DDSD_CAPS = 0x1,
  69743. //DDSD_HEIGHT = 0x2,
  69744. //DDSD_WIDTH = 0x4,
  69745. //DDSD_PITCH = 0x8,
  69746. //DDSD_PIXELFORMAT = 0x1000,
  69747. DDSD_MIPMAPCOUNT = 0x20000;
  69748. //DDSD_LINEARSIZE = 0x80000,
  69749. //DDSD_DEPTH = 0x800000;
  69750. // var DDSCAPS_COMPLEX = 0x8,
  69751. // DDSCAPS_MIPMAP = 0x400000,
  69752. // DDSCAPS_TEXTURE = 0x1000;
  69753. var DDSCAPS2_CUBEMAP = 0x200;
  69754. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  69755. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  69756. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  69757. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  69758. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  69759. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  69760. // DDSCAPS2_VOLUME = 0x200000;
  69761. var
  69762. //DDPF_ALPHAPIXELS = 0x1,
  69763. //DDPF_ALPHA = 0x2,
  69764. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  69765. //DDPF_YUV = 0x200,
  69766. DDPF_LUMINANCE = 0x20000;
  69767. function FourCCToInt32(value) {
  69768. return value.charCodeAt(0) +
  69769. (value.charCodeAt(1) << 8) +
  69770. (value.charCodeAt(2) << 16) +
  69771. (value.charCodeAt(3) << 24);
  69772. }
  69773. function Int32ToFourCC(value) {
  69774. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  69775. }
  69776. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  69777. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  69778. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  69779. var FOURCC_DX10 = FourCCToInt32("DX10");
  69780. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  69781. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  69782. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  69783. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  69784. var headerLengthInt = 31; // The header length in 32 bit ints
  69785. // Offsets into the header array
  69786. var off_magic = 0;
  69787. var off_size = 1;
  69788. var off_flags = 2;
  69789. var off_height = 3;
  69790. var off_width = 4;
  69791. var off_mipmapCount = 7;
  69792. var off_pfFlags = 20;
  69793. var off_pfFourCC = 21;
  69794. var off_RGBbpp = 22;
  69795. // var off_RMask = 23;
  69796. // var off_GMask = 24;
  69797. // var off_BMask = 25;
  69798. // var off_AMask = 26;
  69799. // var off_caps1 = 27;
  69800. var off_caps2 = 28;
  69801. // var off_caps3 = 29;
  69802. // var off_caps4 = 30;
  69803. var off_dxgiFormat = 32;
  69804. ;
  69805. var DDSTools = /** @class */ (function () {
  69806. function DDSTools() {
  69807. }
  69808. DDSTools.GetDDSInfo = function (arrayBuffer) {
  69809. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  69810. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  69811. var mipmapCount = 1;
  69812. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  69813. mipmapCount = Math.max(1, header[off_mipmapCount]);
  69814. }
  69815. var fourCC = header[off_pfFourCC];
  69816. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  69817. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  69818. switch (fourCC) {
  69819. case FOURCC_D3DFMT_R16G16B16A16F:
  69820. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  69821. break;
  69822. case FOURCC_D3DFMT_R32G32B32A32F:
  69823. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  69824. break;
  69825. case FOURCC_DX10:
  69826. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  69827. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  69828. break;
  69829. }
  69830. }
  69831. return {
  69832. width: header[off_width],
  69833. height: header[off_height],
  69834. mipmapCount: mipmapCount,
  69835. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  69836. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  69837. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  69838. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  69839. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  69840. dxgiFormat: dxgiFormat,
  69841. textureType: textureType
  69842. };
  69843. };
  69844. DDSTools._ToHalfFloat = function (value) {
  69845. if (!DDSTools._FloatView) {
  69846. DDSTools._FloatView = new Float32Array(1);
  69847. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  69848. }
  69849. DDSTools._FloatView[0] = value;
  69850. var x = DDSTools._Int32View[0];
  69851. var bits = (x >> 16) & 0x8000; /* Get the sign */
  69852. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  69853. var e = (x >> 23) & 0xff; /* Using int is faster here */
  69854. /* If zero, or denormal, or exponent underflows too much for a denormal
  69855. * half, return signed zero. */
  69856. if (e < 103) {
  69857. return bits;
  69858. }
  69859. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  69860. if (e > 142) {
  69861. bits |= 0x7c00;
  69862. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  69863. * not Inf, so make sure we set one mantissa bit too. */
  69864. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  69865. return bits;
  69866. }
  69867. /* If exponent underflows but not too much, return a denormal */
  69868. if (e < 113) {
  69869. m |= 0x0800;
  69870. /* Extra rounding may overflow and set mantissa to 0 and exponent
  69871. * to 1, which is OK. */
  69872. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  69873. return bits;
  69874. }
  69875. bits |= ((e - 112) << 10) | (m >> 1);
  69876. bits += m & 1;
  69877. return bits;
  69878. };
  69879. DDSTools._FromHalfFloat = function (value) {
  69880. var s = (value & 0x8000) >> 15;
  69881. var e = (value & 0x7C00) >> 10;
  69882. var f = value & 0x03FF;
  69883. if (e === 0) {
  69884. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  69885. }
  69886. else if (e == 0x1F) {
  69887. return f ? NaN : ((s ? -1 : 1) * Infinity);
  69888. }
  69889. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  69890. };
  69891. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  69892. var destArray = new Float32Array(dataLength);
  69893. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  69894. var index = 0;
  69895. for (var y = 0; y < height; y++) {
  69896. for (var x = 0; x < width; x++) {
  69897. var srcPos = (x + y * width) * 4;
  69898. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  69899. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  69900. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  69901. if (DDSTools.StoreLODInAlphaChannel) {
  69902. destArray[index + 3] = lod;
  69903. }
  69904. else {
  69905. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  69906. }
  69907. index += 4;
  69908. }
  69909. }
  69910. return destArray;
  69911. };
  69912. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  69913. if (DDSTools.StoreLODInAlphaChannel) {
  69914. var destArray = new Uint16Array(dataLength);
  69915. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  69916. var index = 0;
  69917. for (var y = 0; y < height; y++) {
  69918. for (var x = 0; x < width; x++) {
  69919. var srcPos = (x + y * width) * 4;
  69920. destArray[index] = srcData[srcPos];
  69921. destArray[index + 1] = srcData[srcPos + 1];
  69922. destArray[index + 2] = srcData[srcPos + 2];
  69923. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  69924. index += 4;
  69925. }
  69926. }
  69927. return destArray;
  69928. }
  69929. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  69930. };
  69931. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  69932. if (DDSTools.StoreLODInAlphaChannel) {
  69933. var destArray = new Float32Array(dataLength);
  69934. var srcData = new Float32Array(arrayBuffer, dataOffset);
  69935. var index = 0;
  69936. for (var y = 0; y < height; y++) {
  69937. for (var x = 0; x < width; x++) {
  69938. var srcPos = (x + y * width) * 4;
  69939. destArray[index] = srcData[srcPos];
  69940. destArray[index + 1] = srcData[srcPos + 1];
  69941. destArray[index + 2] = srcData[srcPos + 2];
  69942. destArray[index + 3] = lod;
  69943. index += 4;
  69944. }
  69945. }
  69946. return destArray;
  69947. }
  69948. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  69949. };
  69950. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  69951. var destArray = new Uint8Array(dataLength);
  69952. var srcData = new Float32Array(arrayBuffer, dataOffset);
  69953. var index = 0;
  69954. for (var y = 0; y < height; y++) {
  69955. for (var x = 0; x < width; x++) {
  69956. var srcPos = (x + y * width) * 4;
  69957. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  69958. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  69959. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  69960. if (DDSTools.StoreLODInAlphaChannel) {
  69961. destArray[index + 3] = lod;
  69962. }
  69963. else {
  69964. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  69965. }
  69966. index += 4;
  69967. }
  69968. }
  69969. return destArray;
  69970. };
  69971. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  69972. var destArray = new Uint8Array(dataLength);
  69973. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  69974. var index = 0;
  69975. for (var y = 0; y < height; y++) {
  69976. for (var x = 0; x < width; x++) {
  69977. var srcPos = (x + y * width) * 4;
  69978. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  69979. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  69980. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  69981. if (DDSTools.StoreLODInAlphaChannel) {
  69982. destArray[index + 3] = lod;
  69983. }
  69984. else {
  69985. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  69986. }
  69987. index += 4;
  69988. }
  69989. }
  69990. return destArray;
  69991. };
  69992. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  69993. var byteArray = new Uint8Array(dataLength);
  69994. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  69995. var index = 0;
  69996. for (var y = 0; y < height; y++) {
  69997. for (var x = 0; x < width; x++) {
  69998. var srcPos = (x + y * width) * 4;
  69999. byteArray[index] = srcData[srcPos + 2];
  70000. byteArray[index + 1] = srcData[srcPos + 1];
  70001. byteArray[index + 2] = srcData[srcPos];
  70002. byteArray[index + 3] = srcData[srcPos + 3];
  70003. index += 4;
  70004. }
  70005. }
  70006. return byteArray;
  70007. };
  70008. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  70009. var byteArray = new Uint8Array(dataLength);
  70010. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  70011. var index = 0;
  70012. for (var y = 0; y < height; y++) {
  70013. for (var x = 0; x < width; x++) {
  70014. var srcPos = (x + y * width) * 3;
  70015. byteArray[index] = srcData[srcPos + 2];
  70016. byteArray[index + 1] = srcData[srcPos + 1];
  70017. byteArray[index + 2] = srcData[srcPos];
  70018. index += 3;
  70019. }
  70020. }
  70021. return byteArray;
  70022. };
  70023. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  70024. var byteArray = new Uint8Array(dataLength);
  70025. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  70026. var index = 0;
  70027. for (var y = 0; y < height; y++) {
  70028. for (var x = 0; x < width; x++) {
  70029. var srcPos = (x + y * width);
  70030. byteArray[index] = srcData[srcPos];
  70031. index++;
  70032. }
  70033. }
  70034. return byteArray;
  70035. };
  70036. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  70037. if (lodIndex === void 0) { lodIndex = -1; }
  70038. var ext = engine.getCaps().s3tc;
  70039. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  70040. var fourCC, width, height, dataLength = 0, dataOffset;
  70041. var byteArray, mipmapCount, mip;
  70042. var internalFormat = 0;
  70043. var format = 0;
  70044. var blockBytes = 1;
  70045. if (header[off_magic] !== DDS_MAGIC) {
  70046. BABYLON.Tools.Error("Invalid magic number in DDS header");
  70047. return;
  70048. }
  70049. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  70050. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  70051. return;
  70052. }
  70053. if (info.isCompressed && !ext) {
  70054. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  70055. return;
  70056. }
  70057. var bpp = header[off_RGBbpp];
  70058. dataOffset = header[off_size] + 4;
  70059. var computeFormats = false;
  70060. if (info.isFourCC) {
  70061. fourCC = header[off_pfFourCC];
  70062. switch (fourCC) {
  70063. case FOURCC_DXT1:
  70064. blockBytes = 8;
  70065. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  70066. break;
  70067. case FOURCC_DXT3:
  70068. blockBytes = 16;
  70069. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  70070. break;
  70071. case FOURCC_DXT5:
  70072. blockBytes = 16;
  70073. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  70074. break;
  70075. case FOURCC_D3DFMT_R16G16B16A16F:
  70076. computeFormats = true;
  70077. break;
  70078. case FOURCC_D3DFMT_R32G32B32A32F:
  70079. computeFormats = true;
  70080. break;
  70081. case FOURCC_DX10:
  70082. // There is an additionnal header so dataOffset need to be changed
  70083. dataOffset += 5 * 4; // 5 uints
  70084. var supported = false;
  70085. switch (info.dxgiFormat) {
  70086. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  70087. computeFormats = true;
  70088. supported = true;
  70089. break;
  70090. case DXGI_FORMAT_B8G8R8X8_UNORM:
  70091. info.isRGB = true;
  70092. info.isFourCC = false;
  70093. bpp = 32;
  70094. supported = true;
  70095. break;
  70096. }
  70097. if (supported) {
  70098. break;
  70099. }
  70100. default:
  70101. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  70102. return;
  70103. }
  70104. }
  70105. if (computeFormats) {
  70106. format = engine._getWebGLTextureType(info.textureType);
  70107. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  70108. }
  70109. mipmapCount = 1;
  70110. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  70111. mipmapCount = Math.max(1, header[off_mipmapCount]);
  70112. }
  70113. for (var face = 0; face < faces; face++) {
  70114. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  70115. width = header[off_width];
  70116. height = header[off_height];
  70117. for (mip = 0; mip < mipmapCount; ++mip) {
  70118. if (lodIndex === -1 || lodIndex === mip) {
  70119. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  70120. var i = (lodIndex === -1) ? mip : 0;
  70121. if (!info.isCompressed && info.isFourCC) {
  70122. dataLength = width * height * 4;
  70123. var floatArray = null;
  70124. if (engine.badOS || engine.badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  70125. if (bpp === 128) {
  70126. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  70127. }
  70128. else if (bpp === 64) {
  70129. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  70130. }
  70131. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  70132. format = engine._getWebGLTextureType(info.textureType);
  70133. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  70134. }
  70135. else {
  70136. if (bpp === 128) {
  70137. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  70138. }
  70139. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  70140. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  70141. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  70142. format = engine._getWebGLTextureType(info.textureType);
  70143. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  70144. }
  70145. else {
  70146. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  70147. }
  70148. }
  70149. if (floatArray) {
  70150. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  70151. }
  70152. }
  70153. else if (info.isRGB) {
  70154. if (bpp === 24) {
  70155. dataLength = width * height * 3;
  70156. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  70157. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  70158. }
  70159. else {
  70160. dataLength = width * height * 4;
  70161. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  70162. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  70163. }
  70164. }
  70165. else if (info.isLuminance) {
  70166. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  70167. var unpaddedRowSize = width;
  70168. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  70169. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  70170. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  70171. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  70172. }
  70173. else {
  70174. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  70175. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  70176. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  70177. }
  70178. }
  70179. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  70180. width *= 0.5;
  70181. height *= 0.5;
  70182. width = Math.max(1.0, width);
  70183. height = Math.max(1.0, height);
  70184. }
  70185. if (currentFace !== undefined) {
  70186. // Loading a single face
  70187. break;
  70188. }
  70189. }
  70190. };
  70191. DDSTools.StoreLODInAlphaChannel = false;
  70192. return DDSTools;
  70193. }());
  70194. Internals.DDSTools = DDSTools;
  70195. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  70196. })(BABYLON || (BABYLON = {}));
  70197. //# sourceMappingURL=babylon.dds.js.map
  70198. var BABYLON;
  70199. (function (BABYLON) {
  70200. var Internals;
  70201. (function (Internals) {
  70202. /**
  70203. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  70204. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  70205. */
  70206. var KhronosTextureContainer = /** @class */ (function () {
  70207. /**
  70208. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  70209. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  70210. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  70211. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  70212. */
  70213. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  70214. this.arrayBuffer = arrayBuffer;
  70215. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  70216. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  70217. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  70218. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  70219. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  70220. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  70221. BABYLON.Tools.Error("texture missing KTX identifier");
  70222. return;
  70223. }
  70224. // load the reset of the header in native 32 bit int
  70225. var header = new Int32Array(this.arrayBuffer, 12, 13);
  70226. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  70227. var oppositeEndianess = header[0] === 0x01020304;
  70228. // read all the header elements in order they exist in the file, without modification (sans endainness)
  70229. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  70230. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  70231. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  70232. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  70233. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  70234. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  70235. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  70236. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  70237. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  70238. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  70239. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  70240. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  70241. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  70242. if (this.glType !== 0) {
  70243. BABYLON.Tools.Error("only compressed formats currently supported");
  70244. return;
  70245. }
  70246. else {
  70247. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  70248. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  70249. }
  70250. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  70251. BABYLON.Tools.Error("only 2D textures currently supported");
  70252. return;
  70253. }
  70254. if (this.numberOfArrayElements !== 0) {
  70255. BABYLON.Tools.Error("texture arrays not currently supported");
  70256. return;
  70257. }
  70258. if (this.numberOfFaces !== facesExpected) {
  70259. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  70260. return;
  70261. }
  70262. // we now have a completely validated file, so could use existence of loadType as success
  70263. // would need to make this more elaborate & adjust checks above to support more than one load type
  70264. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  70265. }
  70266. // not as fast hardware based, but will probably never need to use
  70267. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  70268. return ((val & 0xFF) << 24)
  70269. | ((val & 0xFF00) << 8)
  70270. | ((val >> 8) & 0xFF00)
  70271. | ((val >> 24) & 0xFF);
  70272. };
  70273. /**
  70274. * It is assumed that the texture has already been created & is currently bound
  70275. */
  70276. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  70277. switch (this.loadType) {
  70278. case KhronosTextureContainer.COMPRESSED_2D:
  70279. this._upload2DCompressedLevels(gl, loadMipmaps);
  70280. break;
  70281. case KhronosTextureContainer.TEX_2D:
  70282. case KhronosTextureContainer.COMPRESSED_3D:
  70283. case KhronosTextureContainer.TEX_3D:
  70284. }
  70285. };
  70286. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  70287. // initialize width & height for level 1
  70288. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  70289. var width = this.pixelWidth;
  70290. var height = this.pixelHeight;
  70291. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  70292. for (var level = 0; level < mipmapCount; level++) {
  70293. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  70294. for (var face = 0; face < this.numberOfFaces; face++) {
  70295. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  70296. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  70297. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  70298. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  70299. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  70300. }
  70301. width = Math.max(1.0, width * 0.5);
  70302. height = Math.max(1.0, height * 0.5);
  70303. }
  70304. };
  70305. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  70306. // load types
  70307. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  70308. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  70309. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  70310. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  70311. return KhronosTextureContainer;
  70312. }());
  70313. Internals.KhronosTextureContainer = KhronosTextureContainer;
  70314. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  70315. })(BABYLON || (BABYLON = {}));
  70316. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  70317. var BABYLON;
  70318. (function (BABYLON) {
  70319. var Debug;
  70320. (function (Debug) {
  70321. /**
  70322. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  70323. */
  70324. var SkeletonViewer = /** @class */ (function () {
  70325. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  70326. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  70327. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  70328. this.skeleton = skeleton;
  70329. this.mesh = mesh;
  70330. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  70331. this.renderingGroupId = renderingGroupId;
  70332. this.color = BABYLON.Color3.White();
  70333. this._debugLines = new Array();
  70334. this._isEnabled = false;
  70335. this._scene = scene;
  70336. this.update();
  70337. this._renderFunction = this.update.bind(this);
  70338. }
  70339. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  70340. get: function () {
  70341. return this._isEnabled;
  70342. },
  70343. set: function (value) {
  70344. if (this._isEnabled === value) {
  70345. return;
  70346. }
  70347. this._isEnabled = value;
  70348. if (value) {
  70349. this._scene.registerBeforeRender(this._renderFunction);
  70350. }
  70351. else {
  70352. this._scene.unregisterBeforeRender(this._renderFunction);
  70353. }
  70354. },
  70355. enumerable: true,
  70356. configurable: true
  70357. });
  70358. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  70359. if (x === void 0) { x = 0; }
  70360. if (y === void 0) { y = 0; }
  70361. if (z === void 0) { z = 0; }
  70362. var tmat = BABYLON.Tmp.Matrix[0];
  70363. var parentBone = bone.getParent();
  70364. tmat.copyFrom(bone.getLocalMatrix());
  70365. if (x !== 0 || y !== 0 || z !== 0) {
  70366. var tmat2 = BABYLON.Tmp.Matrix[1];
  70367. BABYLON.Matrix.IdentityToRef(tmat2);
  70368. tmat2.m[12] = x;
  70369. tmat2.m[13] = y;
  70370. tmat2.m[14] = z;
  70371. tmat2.multiplyToRef(tmat, tmat);
  70372. }
  70373. if (parentBone) {
  70374. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  70375. }
  70376. tmat.multiplyToRef(meshMat, tmat);
  70377. position.x = tmat.m[12];
  70378. position.y = tmat.m[13];
  70379. position.z = tmat.m[14];
  70380. };
  70381. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  70382. var len = bones.length;
  70383. var meshPos = this.mesh.position;
  70384. for (var i = 0; i < len; i++) {
  70385. var bone = bones[i];
  70386. var points = this._debugLines[i];
  70387. if (!points) {
  70388. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  70389. this._debugLines[i] = points;
  70390. }
  70391. this._getBonePosition(points[0], bone, meshMat);
  70392. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  70393. points[0].subtractInPlace(meshPos);
  70394. points[1].subtractInPlace(meshPos);
  70395. }
  70396. };
  70397. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  70398. var len = bones.length;
  70399. var boneNum = 0;
  70400. var meshPos = this.mesh.position;
  70401. for (var i = len - 1; i >= 0; i--) {
  70402. var childBone = bones[i];
  70403. var parentBone = childBone.getParent();
  70404. if (!parentBone) {
  70405. continue;
  70406. }
  70407. var points = this._debugLines[boneNum];
  70408. if (!points) {
  70409. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  70410. this._debugLines[boneNum] = points;
  70411. }
  70412. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  70413. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  70414. points[0].subtractInPlace(meshPos);
  70415. points[1].subtractInPlace(meshPos);
  70416. boneNum++;
  70417. }
  70418. };
  70419. SkeletonViewer.prototype.update = function () {
  70420. if (this.autoUpdateBonesMatrices) {
  70421. this.skeleton.computeAbsoluteTransforms();
  70422. }
  70423. if (this.skeleton.bones[0].length === undefined) {
  70424. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  70425. }
  70426. else {
  70427. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  70428. }
  70429. if (!this._debugMesh) {
  70430. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  70431. this._debugMesh.renderingGroupId = this.renderingGroupId;
  70432. }
  70433. else {
  70434. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  70435. }
  70436. this._debugMesh.position.copyFrom(this.mesh.position);
  70437. this._debugMesh.color = this.color;
  70438. };
  70439. SkeletonViewer.prototype.dispose = function () {
  70440. if (this._debugMesh) {
  70441. this.isEnabled = false;
  70442. this._debugMesh.dispose();
  70443. this._debugMesh = null;
  70444. }
  70445. };
  70446. return SkeletonViewer;
  70447. }());
  70448. Debug.SkeletonViewer = SkeletonViewer;
  70449. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  70450. })(BABYLON || (BABYLON = {}));
  70451. //# sourceMappingURL=babylon.skeletonViewer.js.map
  70452. var BABYLON;
  70453. (function (BABYLON) {
  70454. var Debug;
  70455. (function (Debug) {
  70456. var AxesViewer = /** @class */ (function () {
  70457. function AxesViewer(scene, scaleLines) {
  70458. if (scaleLines === void 0) { scaleLines = 1; }
  70459. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  70460. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  70461. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  70462. this.scaleLines = 1;
  70463. this.scaleLines = scaleLines;
  70464. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  70465. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  70466. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  70467. this._xmesh.renderingGroupId = 2;
  70468. this._ymesh.renderingGroupId = 2;
  70469. this._zmesh.renderingGroupId = 2;
  70470. this._xmesh.material.checkReadyOnlyOnce = true;
  70471. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  70472. this._ymesh.material.checkReadyOnlyOnce = true;
  70473. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  70474. this._zmesh.material.checkReadyOnlyOnce = true;
  70475. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  70476. this.scene = scene;
  70477. }
  70478. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  70479. var scaleLines = this.scaleLines;
  70480. if (this._xmesh) {
  70481. this._xmesh.position.copyFrom(position);
  70482. }
  70483. if (this._ymesh) {
  70484. this._ymesh.position.copyFrom(position);
  70485. }
  70486. if (this._zmesh) {
  70487. this._zmesh.position.copyFrom(position);
  70488. }
  70489. var point2 = this._xline[1];
  70490. point2.x = xaxis.x * scaleLines;
  70491. point2.y = xaxis.y * scaleLines;
  70492. point2.z = xaxis.z * scaleLines;
  70493. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  70494. point2 = this._yline[1];
  70495. point2.x = yaxis.x * scaleLines;
  70496. point2.y = yaxis.y * scaleLines;
  70497. point2.z = yaxis.z * scaleLines;
  70498. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  70499. point2 = this._zline[1];
  70500. point2.x = zaxis.x * scaleLines;
  70501. point2.y = zaxis.y * scaleLines;
  70502. point2.z = zaxis.z * scaleLines;
  70503. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  70504. };
  70505. AxesViewer.prototype.dispose = function () {
  70506. if (this._xmesh) {
  70507. this._xmesh.dispose();
  70508. }
  70509. if (this._ymesh) {
  70510. this._ymesh.dispose();
  70511. }
  70512. if (this._zmesh) {
  70513. this._zmesh.dispose();
  70514. }
  70515. this._xmesh = null;
  70516. this._ymesh = null;
  70517. this._zmesh = null;
  70518. this.scene = null;
  70519. };
  70520. return AxesViewer;
  70521. }());
  70522. Debug.AxesViewer = AxesViewer;
  70523. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  70524. })(BABYLON || (BABYLON = {}));
  70525. //# sourceMappingURL=babylon.axesViewer.js.map
  70526. var BABYLON;
  70527. (function (BABYLON) {
  70528. var Debug;
  70529. (function (Debug) {
  70530. var BoneAxesViewer = /** @class */ (function (_super) {
  70531. __extends(BoneAxesViewer, _super);
  70532. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  70533. if (scaleLines === void 0) { scaleLines = 1; }
  70534. var _this = _super.call(this, scene, scaleLines) || this;
  70535. _this.pos = BABYLON.Vector3.Zero();
  70536. _this.xaxis = BABYLON.Vector3.Zero();
  70537. _this.yaxis = BABYLON.Vector3.Zero();
  70538. _this.zaxis = BABYLON.Vector3.Zero();
  70539. _this.mesh = mesh;
  70540. _this.bone = bone;
  70541. return _this;
  70542. }
  70543. BoneAxesViewer.prototype.update = function () {
  70544. if (!this.mesh || !this.bone) {
  70545. return;
  70546. }
  70547. var bone = this.bone;
  70548. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  70549. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  70550. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  70551. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  70552. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  70553. };
  70554. BoneAxesViewer.prototype.dispose = function () {
  70555. if (this.mesh) {
  70556. this.mesh = null;
  70557. this.bone = null;
  70558. _super.prototype.dispose.call(this);
  70559. }
  70560. };
  70561. return BoneAxesViewer;
  70562. }(Debug.AxesViewer));
  70563. Debug.BoneAxesViewer = BoneAxesViewer;
  70564. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  70565. })(BABYLON || (BABYLON = {}));
  70566. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  70567. var BABYLON;
  70568. (function (BABYLON) {
  70569. var RayHelper = /** @class */ (function () {
  70570. function RayHelper(ray) {
  70571. this.ray = ray;
  70572. }
  70573. RayHelper.CreateAndShow = function (ray, scene, color) {
  70574. var helper = new RayHelper(ray);
  70575. helper.show(scene, color);
  70576. return helper;
  70577. };
  70578. RayHelper.prototype.show = function (scene, color) {
  70579. if (!this._renderFunction && this.ray) {
  70580. var ray = this.ray;
  70581. this._renderFunction = this._render.bind(this);
  70582. this._scene = scene;
  70583. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  70584. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  70585. if (this._renderFunction) {
  70586. this._scene.registerBeforeRender(this._renderFunction);
  70587. }
  70588. }
  70589. if (color && this._renderLine) {
  70590. this._renderLine.color.copyFrom(color);
  70591. }
  70592. };
  70593. RayHelper.prototype.hide = function () {
  70594. if (this._renderFunction && this._scene) {
  70595. this._scene.unregisterBeforeRender(this._renderFunction);
  70596. this._scene = null;
  70597. this._renderFunction = null;
  70598. if (this._renderLine) {
  70599. this._renderLine.dispose();
  70600. this._renderLine = null;
  70601. }
  70602. this._renderPoints = [];
  70603. }
  70604. };
  70605. RayHelper.prototype._render = function () {
  70606. var ray = this.ray;
  70607. if (!ray) {
  70608. return;
  70609. }
  70610. var point = this._renderPoints[1];
  70611. var len = Math.min(ray.length, 1000000);
  70612. point.copyFrom(ray.direction);
  70613. point.scaleInPlace(len);
  70614. point.addInPlace(ray.origin);
  70615. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  70616. };
  70617. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  70618. this._attachedToMesh = mesh;
  70619. var ray = this.ray;
  70620. if (!ray) {
  70621. return;
  70622. }
  70623. if (!ray.direction) {
  70624. ray.direction = BABYLON.Vector3.Zero();
  70625. }
  70626. if (!ray.origin) {
  70627. ray.origin = BABYLON.Vector3.Zero();
  70628. }
  70629. if (length) {
  70630. ray.length = length;
  70631. }
  70632. if (!meshSpaceOrigin) {
  70633. meshSpaceOrigin = BABYLON.Vector3.Zero();
  70634. }
  70635. if (!meshSpaceDirection) {
  70636. // -1 so that this will work with Mesh.lookAt
  70637. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  70638. }
  70639. if (!this._meshSpaceDirection) {
  70640. this._meshSpaceDirection = meshSpaceDirection.clone();
  70641. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  70642. }
  70643. else {
  70644. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  70645. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  70646. }
  70647. if (!this._updateToMeshFunction) {
  70648. this._updateToMeshFunction = this._updateToMesh.bind(this);
  70649. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  70650. }
  70651. this._updateToMesh();
  70652. };
  70653. RayHelper.prototype.detachFromMesh = function () {
  70654. if (this._attachedToMesh) {
  70655. if (this._updateToMeshFunction) {
  70656. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  70657. }
  70658. this._attachedToMesh = null;
  70659. this._updateToMeshFunction = null;
  70660. }
  70661. };
  70662. RayHelper.prototype._updateToMesh = function () {
  70663. var ray = this.ray;
  70664. if (!this._attachedToMesh || !ray) {
  70665. return;
  70666. }
  70667. if (this._attachedToMesh._isDisposed) {
  70668. this.detachFromMesh();
  70669. return;
  70670. }
  70671. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  70672. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  70673. };
  70674. RayHelper.prototype.dispose = function () {
  70675. this.hide();
  70676. this.detachFromMesh();
  70677. this.ray = null;
  70678. };
  70679. return RayHelper;
  70680. }());
  70681. BABYLON.RayHelper = RayHelper;
  70682. })(BABYLON || (BABYLON = {}));
  70683. //# sourceMappingURL=babylon.rayHelper.js.map
  70684. var BABYLON;
  70685. (function (BABYLON) {
  70686. // load the inspector using require, if not present in the global namespace.
  70687. var DebugLayer = /** @class */ (function () {
  70688. function DebugLayer(scene) {
  70689. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  70690. this._scene = scene;
  70691. // load inspector using require, if it doesn't exist on the global namespace.
  70692. }
  70693. /** Creates the inspector window. */
  70694. DebugLayer.prototype._createInspector = function (config) {
  70695. if (config === void 0) { config = {}; }
  70696. var popup = config.popup || false;
  70697. var initialTab = config.initialTab || 0;
  70698. var parentElement = config.parentElement || null;
  70699. if (!this._inspector) {
  70700. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  70701. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  70702. } // else nothing to do,; instance is already existing
  70703. };
  70704. DebugLayer.prototype.isVisible = function () {
  70705. if (!this._inspector) {
  70706. return false;
  70707. }
  70708. return true;
  70709. };
  70710. DebugLayer.prototype.hide = function () {
  70711. if (this._inspector) {
  70712. try {
  70713. this._inspector.dispose();
  70714. }
  70715. catch (e) {
  70716. // If the inspector has been removed directly from the inspector tool
  70717. }
  70718. this._inspector = null;
  70719. }
  70720. };
  70721. DebugLayer.prototype.show = function (config) {
  70722. if (config === void 0) { config = {}; }
  70723. if (typeof this.BJSINSPECTOR == 'undefined') {
  70724. // Load inspector and add it to the DOM
  70725. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  70726. }
  70727. else {
  70728. // Otherwise creates the inspector
  70729. this._createInspector(config);
  70730. }
  70731. };
  70732. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  70733. return DebugLayer;
  70734. }());
  70735. BABYLON.DebugLayer = DebugLayer;
  70736. })(BABYLON || (BABYLON = {}));
  70737. //# sourceMappingURL=babylon.debugLayer.js.map
  70738. var BABYLON;
  70739. (function (BABYLON) {
  70740. var Debug;
  70741. (function (Debug) {
  70742. var PhysicsViewer = /** @class */ (function () {
  70743. function PhysicsViewer(scene) {
  70744. this._impostors = [];
  70745. this._meshes = [];
  70746. this._numMeshes = 0;
  70747. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  70748. var physicEngine = this._scene.getPhysicsEngine();
  70749. if (physicEngine) {
  70750. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  70751. }
  70752. }
  70753. PhysicsViewer.prototype._updateDebugMeshes = function () {
  70754. var plugin = this._physicsEnginePlugin;
  70755. for (var i = 0; i < this._numMeshes; i++) {
  70756. var impostor = this._impostors[i];
  70757. if (!impostor) {
  70758. continue;
  70759. }
  70760. if (impostor.isDisposed) {
  70761. this.hideImpostor(this._impostors[i--]);
  70762. }
  70763. else {
  70764. var mesh = this._meshes[i];
  70765. if (mesh && plugin) {
  70766. plugin.syncMeshWithImpostor(mesh, impostor);
  70767. }
  70768. }
  70769. }
  70770. };
  70771. PhysicsViewer.prototype.showImpostor = function (impostor) {
  70772. if (!this._scene) {
  70773. return;
  70774. }
  70775. for (var i = 0; i < this._numMeshes; i++) {
  70776. if (this._impostors[i] == impostor) {
  70777. return;
  70778. }
  70779. }
  70780. var debugMesh = this._getDebugMesh(impostor, this._scene);
  70781. if (debugMesh) {
  70782. this._impostors[this._numMeshes] = impostor;
  70783. this._meshes[this._numMeshes] = debugMesh;
  70784. if (this._numMeshes === 0) {
  70785. this._renderFunction = this._updateDebugMeshes.bind(this);
  70786. this._scene.registerBeforeRender(this._renderFunction);
  70787. }
  70788. this._numMeshes++;
  70789. }
  70790. };
  70791. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  70792. if (!impostor || !this._scene) {
  70793. return;
  70794. }
  70795. var removed = false;
  70796. for (var i = 0; i < this._numMeshes; i++) {
  70797. if (this._impostors[i] == impostor) {
  70798. var mesh = this._meshes[i];
  70799. if (!mesh) {
  70800. continue;
  70801. }
  70802. this._scene.removeMesh(mesh);
  70803. mesh.dispose();
  70804. this._numMeshes--;
  70805. if (this._numMeshes > 0) {
  70806. this._meshes[i] = this._meshes[this._numMeshes];
  70807. this._impostors[i] = this._impostors[this._numMeshes];
  70808. this._meshes[this._numMeshes] = null;
  70809. this._impostors[this._numMeshes] = null;
  70810. }
  70811. else {
  70812. this._meshes[0] = null;
  70813. this._impostors[0] = null;
  70814. }
  70815. removed = true;
  70816. break;
  70817. }
  70818. }
  70819. if (removed && this._numMeshes === 0) {
  70820. this._scene.unregisterBeforeRender(this._renderFunction);
  70821. }
  70822. };
  70823. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  70824. if (!this._debugMaterial) {
  70825. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  70826. this._debugMaterial.wireframe = true;
  70827. }
  70828. return this._debugMaterial;
  70829. };
  70830. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  70831. if (!this._debugBoxMesh) {
  70832. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  70833. this._debugBoxMesh.renderingGroupId = 1;
  70834. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  70835. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  70836. scene.removeMesh(this._debugBoxMesh);
  70837. }
  70838. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  70839. };
  70840. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  70841. if (!this._debugSphereMesh) {
  70842. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  70843. this._debugSphereMesh.renderingGroupId = 1;
  70844. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  70845. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  70846. scene.removeMesh(this._debugSphereMesh);
  70847. }
  70848. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  70849. };
  70850. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  70851. var mesh = null;
  70852. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  70853. mesh = this._getDebugBoxMesh(scene);
  70854. impostor.getBoxSizeToRef(mesh.scaling);
  70855. }
  70856. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  70857. mesh = this._getDebugSphereMesh(scene);
  70858. var radius = impostor.getRadius();
  70859. mesh.scaling.x = radius * 2;
  70860. mesh.scaling.y = radius * 2;
  70861. mesh.scaling.z = radius * 2;
  70862. }
  70863. return mesh;
  70864. };
  70865. PhysicsViewer.prototype.dispose = function () {
  70866. for (var i = 0; i < this._numMeshes; i++) {
  70867. this.hideImpostor(this._impostors[i]);
  70868. }
  70869. if (this._debugBoxMesh) {
  70870. this._debugBoxMesh.dispose();
  70871. }
  70872. if (this._debugSphereMesh) {
  70873. this._debugSphereMesh.dispose();
  70874. }
  70875. if (this._debugMaterial) {
  70876. this._debugMaterial.dispose();
  70877. }
  70878. this._impostors.length = 0;
  70879. this._scene = null;
  70880. this._physicsEnginePlugin = null;
  70881. };
  70882. return PhysicsViewer;
  70883. }());
  70884. Debug.PhysicsViewer = PhysicsViewer;
  70885. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  70886. })(BABYLON || (BABYLON = {}));
  70887. //# sourceMappingURL=babylon.physicsViewer.js.map
  70888. var BABYLON;
  70889. (function (BABYLON) {
  70890. var BoundingBoxRenderer = /** @class */ (function () {
  70891. function BoundingBoxRenderer(scene) {
  70892. this.frontColor = new BABYLON.Color3(1, 1, 1);
  70893. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  70894. this.showBackLines = true;
  70895. this.renderList = new BABYLON.SmartArray(32);
  70896. this._vertexBuffers = {};
  70897. this._scene = scene;
  70898. }
  70899. BoundingBoxRenderer.prototype._prepareRessources = function () {
  70900. if (this._colorShader) {
  70901. return;
  70902. }
  70903. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  70904. attributes: [BABYLON.VertexBuffer.PositionKind],
  70905. uniforms: ["world", "viewProjection", "color"]
  70906. });
  70907. var engine = this._scene.getEngine();
  70908. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  70909. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  70910. this._createIndexBuffer();
  70911. };
  70912. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  70913. var engine = this._scene.getEngine();
  70914. 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]);
  70915. };
  70916. BoundingBoxRenderer.prototype._rebuild = function () {
  70917. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  70918. if (vb) {
  70919. vb._rebuild();
  70920. }
  70921. this._createIndexBuffer();
  70922. };
  70923. BoundingBoxRenderer.prototype.reset = function () {
  70924. this.renderList.reset();
  70925. };
  70926. BoundingBoxRenderer.prototype.render = function () {
  70927. if (this.renderList.length === 0) {
  70928. return;
  70929. }
  70930. this._prepareRessources();
  70931. if (!this._colorShader.isReady()) {
  70932. return;
  70933. }
  70934. var engine = this._scene.getEngine();
  70935. engine.setDepthWrite(false);
  70936. this._colorShader._preBind();
  70937. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  70938. var boundingBox = this.renderList.data[boundingBoxIndex];
  70939. var min = boundingBox.minimum;
  70940. var max = boundingBox.maximum;
  70941. var diff = max.subtract(min);
  70942. var median = min.add(diff.scale(0.5));
  70943. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  70944. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  70945. .multiply(boundingBox.getWorldMatrix());
  70946. // VBOs
  70947. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  70948. if (this.showBackLines) {
  70949. // Back
  70950. engine.setDepthFunctionToGreaterOrEqual();
  70951. this._scene.resetCachedMaterial();
  70952. this._colorShader.setColor4("color", this.backColor.toColor4());
  70953. this._colorShader.bind(worldMatrix);
  70954. // Draw order
  70955. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  70956. }
  70957. // Front
  70958. engine.setDepthFunctionToLess();
  70959. this._scene.resetCachedMaterial();
  70960. this._colorShader.setColor4("color", this.frontColor.toColor4());
  70961. this._colorShader.bind(worldMatrix);
  70962. // Draw order
  70963. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  70964. }
  70965. this._colorShader.unbind();
  70966. engine.setDepthFunctionToLessOrEqual();
  70967. engine.setDepthWrite(true);
  70968. };
  70969. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  70970. this._prepareRessources();
  70971. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  70972. return;
  70973. }
  70974. var engine = this._scene.getEngine();
  70975. engine.setDepthWrite(false);
  70976. engine.setColorWrite(false);
  70977. this._colorShader._preBind();
  70978. var boundingBox = mesh._boundingInfo.boundingBox;
  70979. var min = boundingBox.minimum;
  70980. var max = boundingBox.maximum;
  70981. var diff = max.subtract(min);
  70982. var median = min.add(diff.scale(0.5));
  70983. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  70984. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  70985. .multiply(boundingBox.getWorldMatrix());
  70986. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  70987. engine.setDepthFunctionToLess();
  70988. this._scene.resetCachedMaterial();
  70989. this._colorShader.bind(worldMatrix);
  70990. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 24);
  70991. this._colorShader.unbind();
  70992. engine.setDepthFunctionToLessOrEqual();
  70993. engine.setDepthWrite(true);
  70994. engine.setColorWrite(true);
  70995. };
  70996. BoundingBoxRenderer.prototype.dispose = function () {
  70997. if (!this._colorShader) {
  70998. return;
  70999. }
  71000. this.renderList.dispose();
  71001. this._colorShader.dispose();
  71002. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  71003. if (buffer) {
  71004. buffer.dispose();
  71005. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  71006. }
  71007. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  71008. };
  71009. return BoundingBoxRenderer;
  71010. }());
  71011. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  71012. })(BABYLON || (BABYLON = {}));
  71013. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  71014. var BABYLON;
  71015. (function (BABYLON) {
  71016. var MorphTarget = /** @class */ (function () {
  71017. function MorphTarget(name, influence) {
  71018. if (influence === void 0) { influence = 0; }
  71019. this.name = name;
  71020. this.animations = new Array();
  71021. this._positions = null;
  71022. this._normals = null;
  71023. this._tangents = null;
  71024. this.onInfluenceChanged = new BABYLON.Observable();
  71025. this.influence = influence;
  71026. }
  71027. Object.defineProperty(MorphTarget.prototype, "influence", {
  71028. get: function () {
  71029. return this._influence;
  71030. },
  71031. set: function (influence) {
  71032. if (this._influence === influence) {
  71033. return;
  71034. }
  71035. var previous = this._influence;
  71036. this._influence = influence;
  71037. if (this.onInfluenceChanged.hasObservers) {
  71038. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  71039. }
  71040. },
  71041. enumerable: true,
  71042. configurable: true
  71043. });
  71044. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  71045. get: function () {
  71046. return !!this._positions;
  71047. },
  71048. enumerable: true,
  71049. configurable: true
  71050. });
  71051. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  71052. get: function () {
  71053. return !!this._normals;
  71054. },
  71055. enumerable: true,
  71056. configurable: true
  71057. });
  71058. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  71059. get: function () {
  71060. return !!this._tangents;
  71061. },
  71062. enumerable: true,
  71063. configurable: true
  71064. });
  71065. MorphTarget.prototype.setPositions = function (data) {
  71066. this._positions = data;
  71067. };
  71068. MorphTarget.prototype.getPositions = function () {
  71069. return this._positions;
  71070. };
  71071. MorphTarget.prototype.setNormals = function (data) {
  71072. this._normals = data;
  71073. };
  71074. MorphTarget.prototype.getNormals = function () {
  71075. return this._normals;
  71076. };
  71077. MorphTarget.prototype.setTangents = function (data) {
  71078. this._tangents = data;
  71079. };
  71080. MorphTarget.prototype.getTangents = function () {
  71081. return this._tangents;
  71082. };
  71083. /**
  71084. * Serializes the current target into a Serialization object.
  71085. * Returns the serialized object.
  71086. */
  71087. MorphTarget.prototype.serialize = function () {
  71088. var serializationObject = {};
  71089. serializationObject.name = this.name;
  71090. serializationObject.influence = this.influence;
  71091. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  71092. if (this.hasNormals) {
  71093. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  71094. }
  71095. if (this.hasTangents) {
  71096. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  71097. }
  71098. // Animations
  71099. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  71100. return serializationObject;
  71101. };
  71102. // Statics
  71103. MorphTarget.Parse = function (serializationObject) {
  71104. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  71105. result.setPositions(serializationObject.positions);
  71106. if (serializationObject.normals) {
  71107. result.setNormals(serializationObject.normals);
  71108. }
  71109. if (serializationObject.tangents) {
  71110. result.setTangents(serializationObject.tangents);
  71111. }
  71112. // Animations
  71113. if (serializationObject.animations) {
  71114. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  71115. var parsedAnimation = serializationObject.animations[animationIndex];
  71116. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  71117. }
  71118. }
  71119. return result;
  71120. };
  71121. MorphTarget.FromMesh = function (mesh, name, influence) {
  71122. if (!name) {
  71123. name = mesh.name;
  71124. }
  71125. var result = new MorphTarget(name, influence);
  71126. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  71127. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  71128. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  71129. }
  71130. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  71131. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  71132. }
  71133. return result;
  71134. };
  71135. return MorphTarget;
  71136. }());
  71137. BABYLON.MorphTarget = MorphTarget;
  71138. })(BABYLON || (BABYLON = {}));
  71139. //# sourceMappingURL=babylon.morphTarget.js.map
  71140. var BABYLON;
  71141. (function (BABYLON) {
  71142. var MorphTargetManager = /** @class */ (function () {
  71143. function MorphTargetManager(scene) {
  71144. if (scene === void 0) { scene = null; }
  71145. this._targets = new Array();
  71146. this._targetObservable = new Array();
  71147. this._activeTargets = new BABYLON.SmartArray(16);
  71148. this._supportsNormals = false;
  71149. this._supportsTangents = false;
  71150. this._vertexCount = 0;
  71151. this._uniqueId = 0;
  71152. this._tempInfluences = new Array();
  71153. if (!scene) {
  71154. scene = BABYLON.Engine.LastCreatedScene;
  71155. }
  71156. this._scene = scene;
  71157. if (this._scene) {
  71158. this._scene.morphTargetManagers.push(this);
  71159. this._uniqueId = this._scene.getUniqueId();
  71160. }
  71161. }
  71162. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  71163. get: function () {
  71164. return this._uniqueId;
  71165. },
  71166. enumerable: true,
  71167. configurable: true
  71168. });
  71169. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  71170. get: function () {
  71171. return this._vertexCount;
  71172. },
  71173. enumerable: true,
  71174. configurable: true
  71175. });
  71176. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  71177. get: function () {
  71178. return this._supportsNormals;
  71179. },
  71180. enumerable: true,
  71181. configurable: true
  71182. });
  71183. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  71184. get: function () {
  71185. return this._supportsTangents;
  71186. },
  71187. enumerable: true,
  71188. configurable: true
  71189. });
  71190. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  71191. get: function () {
  71192. return this._targets.length;
  71193. },
  71194. enumerable: true,
  71195. configurable: true
  71196. });
  71197. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  71198. get: function () {
  71199. return this._activeTargets.length;
  71200. },
  71201. enumerable: true,
  71202. configurable: true
  71203. });
  71204. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  71205. get: function () {
  71206. return this._influences;
  71207. },
  71208. enumerable: true,
  71209. configurable: true
  71210. });
  71211. MorphTargetManager.prototype.getActiveTarget = function (index) {
  71212. return this._activeTargets.data[index];
  71213. };
  71214. MorphTargetManager.prototype.getTarget = function (index) {
  71215. return this._targets[index];
  71216. };
  71217. MorphTargetManager.prototype.addTarget = function (target) {
  71218. var _this = this;
  71219. this._targets.push(target);
  71220. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  71221. _this._syncActiveTargets(needUpdate);
  71222. }));
  71223. this._syncActiveTargets(true);
  71224. };
  71225. MorphTargetManager.prototype.removeTarget = function (target) {
  71226. var index = this._targets.indexOf(target);
  71227. if (index >= 0) {
  71228. this._targets.splice(index, 1);
  71229. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  71230. this._syncActiveTargets(true);
  71231. }
  71232. };
  71233. /**
  71234. * Serializes the current manager into a Serialization object.
  71235. * Returns the serialized object.
  71236. */
  71237. MorphTargetManager.prototype.serialize = function () {
  71238. var serializationObject = {};
  71239. serializationObject.id = this.uniqueId;
  71240. serializationObject.targets = [];
  71241. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  71242. var target = _a[_i];
  71243. serializationObject.targets.push(target.serialize());
  71244. }
  71245. return serializationObject;
  71246. };
  71247. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  71248. var influenceCount = 0;
  71249. this._activeTargets.reset();
  71250. this._supportsNormals = true;
  71251. this._supportsTangents = true;
  71252. this._vertexCount = 0;
  71253. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  71254. var target = _a[_i];
  71255. if (target.influence > 0) {
  71256. this._activeTargets.push(target);
  71257. this._tempInfluences[influenceCount++] = target.influence;
  71258. this._supportsNormals = this._supportsNormals && target.hasNormals;
  71259. this._supportsTangents = this._supportsTangents && target.hasTangents;
  71260. var positions = target.getPositions();
  71261. if (!positions) {
  71262. BABYLON.Tools.Error("Invalid target. Target must positions.");
  71263. return;
  71264. }
  71265. var vertexCount = positions.length / 3;
  71266. if (this._vertexCount === 0) {
  71267. this._vertexCount = vertexCount;
  71268. }
  71269. else if (this._vertexCount !== vertexCount) {
  71270. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  71271. return;
  71272. }
  71273. }
  71274. }
  71275. if (!this._influences || this._influences.length !== influenceCount) {
  71276. this._influences = new Float32Array(influenceCount);
  71277. }
  71278. for (var index = 0; index < influenceCount; index++) {
  71279. this._influences[index] = this._tempInfluences[index];
  71280. }
  71281. if (needUpdate && this._scene) {
  71282. // Flag meshes as dirty to resync with the active targets
  71283. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  71284. var mesh = _c[_b];
  71285. if (mesh.morphTargetManager === this) {
  71286. mesh._syncGeometryWithMorphTargetManager();
  71287. }
  71288. }
  71289. }
  71290. };
  71291. // Statics
  71292. MorphTargetManager.Parse = function (serializationObject, scene) {
  71293. var result = new MorphTargetManager(scene);
  71294. result._uniqueId = serializationObject.id;
  71295. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  71296. var targetData = _a[_i];
  71297. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  71298. }
  71299. return result;
  71300. };
  71301. return MorphTargetManager;
  71302. }());
  71303. BABYLON.MorphTargetManager = MorphTargetManager;
  71304. })(BABYLON || (BABYLON = {}));
  71305. //# sourceMappingURL=babylon.morphTargetManager.js.map
  71306. var BABYLON;
  71307. (function (BABYLON) {
  71308. var Octree = /** @class */ (function () {
  71309. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  71310. if (maxDepth === void 0) { maxDepth = 2; }
  71311. this.maxDepth = maxDepth;
  71312. this.dynamicContent = new Array();
  71313. this._maxBlockCapacity = maxBlockCapacity || 64;
  71314. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  71315. this._creationFunc = creationFunc;
  71316. }
  71317. // Methods
  71318. Octree.prototype.update = function (worldMin, worldMax, entries) {
  71319. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  71320. };
  71321. Octree.prototype.addMesh = function (entry) {
  71322. for (var index = 0; index < this.blocks.length; index++) {
  71323. var block = this.blocks[index];
  71324. block.addEntry(entry);
  71325. }
  71326. };
  71327. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  71328. this._selectionContent.reset();
  71329. for (var index = 0; index < this.blocks.length; index++) {
  71330. var block = this.blocks[index];
  71331. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  71332. }
  71333. if (allowDuplicate) {
  71334. this._selectionContent.concat(this.dynamicContent);
  71335. }
  71336. else {
  71337. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  71338. }
  71339. return this._selectionContent;
  71340. };
  71341. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  71342. this._selectionContent.reset();
  71343. for (var index = 0; index < this.blocks.length; index++) {
  71344. var block = this.blocks[index];
  71345. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  71346. }
  71347. if (allowDuplicate) {
  71348. this._selectionContent.concat(this.dynamicContent);
  71349. }
  71350. else {
  71351. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  71352. }
  71353. return this._selectionContent;
  71354. };
  71355. Octree.prototype.intersectsRay = function (ray) {
  71356. this._selectionContent.reset();
  71357. for (var index = 0; index < this.blocks.length; index++) {
  71358. var block = this.blocks[index];
  71359. block.intersectsRay(ray, this._selectionContent);
  71360. }
  71361. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  71362. return this._selectionContent;
  71363. };
  71364. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  71365. target.blocks = new Array();
  71366. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  71367. // Segmenting space
  71368. for (var x = 0; x < 2; x++) {
  71369. for (var y = 0; y < 2; y++) {
  71370. for (var z = 0; z < 2; z++) {
  71371. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  71372. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  71373. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  71374. block.addEntries(entries);
  71375. target.blocks.push(block);
  71376. }
  71377. }
  71378. }
  71379. };
  71380. Octree.CreationFuncForMeshes = function (entry, block) {
  71381. var boundingInfo = entry.getBoundingInfo();
  71382. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  71383. block.entries.push(entry);
  71384. }
  71385. };
  71386. Octree.CreationFuncForSubMeshes = function (entry, block) {
  71387. var boundingInfo = entry.getBoundingInfo();
  71388. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  71389. block.entries.push(entry);
  71390. }
  71391. };
  71392. return Octree;
  71393. }());
  71394. BABYLON.Octree = Octree;
  71395. })(BABYLON || (BABYLON = {}));
  71396. //# sourceMappingURL=babylon.octree.js.map
  71397. var BABYLON;
  71398. (function (BABYLON) {
  71399. var OctreeBlock = /** @class */ (function () {
  71400. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  71401. this.entries = new Array();
  71402. this._boundingVectors = new Array();
  71403. this._capacity = capacity;
  71404. this._depth = depth;
  71405. this._maxDepth = maxDepth;
  71406. this._creationFunc = creationFunc;
  71407. this._minPoint = minPoint;
  71408. this._maxPoint = maxPoint;
  71409. this._boundingVectors.push(minPoint.clone());
  71410. this._boundingVectors.push(maxPoint.clone());
  71411. this._boundingVectors.push(minPoint.clone());
  71412. this._boundingVectors[2].x = maxPoint.x;
  71413. this._boundingVectors.push(minPoint.clone());
  71414. this._boundingVectors[3].y = maxPoint.y;
  71415. this._boundingVectors.push(minPoint.clone());
  71416. this._boundingVectors[4].z = maxPoint.z;
  71417. this._boundingVectors.push(maxPoint.clone());
  71418. this._boundingVectors[5].z = minPoint.z;
  71419. this._boundingVectors.push(maxPoint.clone());
  71420. this._boundingVectors[6].x = minPoint.x;
  71421. this._boundingVectors.push(maxPoint.clone());
  71422. this._boundingVectors[7].y = minPoint.y;
  71423. }
  71424. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  71425. // Property
  71426. get: function () {
  71427. return this._capacity;
  71428. },
  71429. enumerable: true,
  71430. configurable: true
  71431. });
  71432. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  71433. get: function () {
  71434. return this._minPoint;
  71435. },
  71436. enumerable: true,
  71437. configurable: true
  71438. });
  71439. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  71440. get: function () {
  71441. return this._maxPoint;
  71442. },
  71443. enumerable: true,
  71444. configurable: true
  71445. });
  71446. // Methods
  71447. OctreeBlock.prototype.addEntry = function (entry) {
  71448. if (this.blocks) {
  71449. for (var index = 0; index < this.blocks.length; index++) {
  71450. var block = this.blocks[index];
  71451. block.addEntry(entry);
  71452. }
  71453. return;
  71454. }
  71455. this._creationFunc(entry, this);
  71456. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  71457. this.createInnerBlocks();
  71458. }
  71459. };
  71460. OctreeBlock.prototype.addEntries = function (entries) {
  71461. for (var index = 0; index < entries.length; index++) {
  71462. var mesh = entries[index];
  71463. this.addEntry(mesh);
  71464. }
  71465. };
  71466. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  71467. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  71468. if (this.blocks) {
  71469. for (var index = 0; index < this.blocks.length; index++) {
  71470. var block = this.blocks[index];
  71471. block.select(frustumPlanes, selection, allowDuplicate);
  71472. }
  71473. return;
  71474. }
  71475. if (allowDuplicate) {
  71476. selection.concat(this.entries);
  71477. }
  71478. else {
  71479. selection.concatWithNoDuplicate(this.entries);
  71480. }
  71481. }
  71482. };
  71483. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  71484. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  71485. if (this.blocks) {
  71486. for (var index = 0; index < this.blocks.length; index++) {
  71487. var block = this.blocks[index];
  71488. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  71489. }
  71490. return;
  71491. }
  71492. if (allowDuplicate) {
  71493. selection.concat(this.entries);
  71494. }
  71495. else {
  71496. selection.concatWithNoDuplicate(this.entries);
  71497. }
  71498. }
  71499. };
  71500. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  71501. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  71502. if (this.blocks) {
  71503. for (var index = 0; index < this.blocks.length; index++) {
  71504. var block = this.blocks[index];
  71505. block.intersectsRay(ray, selection);
  71506. }
  71507. return;
  71508. }
  71509. selection.concatWithNoDuplicate(this.entries);
  71510. }
  71511. };
  71512. OctreeBlock.prototype.createInnerBlocks = function () {
  71513. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  71514. };
  71515. return OctreeBlock;
  71516. }());
  71517. BABYLON.OctreeBlock = OctreeBlock;
  71518. })(BABYLON || (BABYLON = {}));
  71519. //# sourceMappingURL=babylon.octreeBlock.js.map
  71520. var BABYLON;
  71521. (function (BABYLON) {
  71522. var SIMDVector3 = /** @class */ (function () {
  71523. function SIMDVector3() {
  71524. }
  71525. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  71526. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD(vector.x, vector.y, vector.z, transformation, result);
  71527. };
  71528. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  71529. var m = transformation.m;
  71530. var m0 = SIMD.Float32x4.load(m, 0);
  71531. var m1 = SIMD.Float32x4.load(m, 4);
  71532. var m2 = SIMD.Float32x4.load(m, 8);
  71533. var m3 = SIMD.Float32x4.load(m, 12);
  71534. var r = SIMD.Float32x4.add(SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.splat(x), m0), SIMD.Float32x4.mul(SIMD.Float32x4.splat(y), m1)), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.splat(z), m2), m3));
  71535. r = SIMD.Float32x4.div(r, SIMD.Float32x4.swizzle(r, 3, 3, 3, 3));
  71536. result.x = SIMD.Float32x4.extractLane(r, 0);
  71537. result.y = SIMD.Float32x4.extractLane(r, 1);
  71538. result.z = SIMD.Float32x4.extractLane(r, 2);
  71539. };
  71540. return SIMDVector3;
  71541. }());
  71542. var SIMDMatrix = /** @class */ (function () {
  71543. function SIMDMatrix() {
  71544. }
  71545. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  71546. var tm = this.m;
  71547. var om = other.m;
  71548. var m0 = SIMD.Float32x4.load(om, 0);
  71549. var m1 = SIMD.Float32x4.load(om, 4);
  71550. var m2 = SIMD.Float32x4.load(om, 8);
  71551. var m3 = SIMD.Float32x4.load(om, 12);
  71552. for (var i = 0; i < 16; i += 4) {
  71553. SIMD.Float32x4.store(result, i + offset, SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.splat(tm[i]), m0), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.splat(tm[i + 1]), m1), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.splat(tm[i + 2]), m2), SIMD.Float32x4.mul(SIMD.Float32x4.splat(tm[i + 3]), m3)))));
  71554. }
  71555. return this;
  71556. };
  71557. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  71558. var src = this.m;
  71559. var dest = other.m;
  71560. // Load the 4 rows
  71561. var src0 = SIMD.Float32x4.load(src, 0);
  71562. var src1 = SIMD.Float32x4.load(src, 4);
  71563. var src2 = SIMD.Float32x4.load(src, 8);
  71564. var src3 = SIMD.Float32x4.load(src, 12);
  71565. // Transpose the source matrix. Sort of. Not a true transpose operation
  71566. var tmp1 = SIMD.Float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  71567. var row1 = SIMD.Float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  71568. var row0 = SIMD.Float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  71569. row1 = SIMD.Float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  71570. tmp1 = SIMD.Float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  71571. var row3 = SIMD.Float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  71572. var row2 = SIMD.Float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  71573. row3 = SIMD.Float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  71574. // This is a true transposition, but it will lead to an incorrect result
  71575. //tmp1 = shuffle(src0, src1, 0, 1, 4, 5);
  71576. //tmp2 = shuffle(src2, src3, 0, 1, 4, 5);
  71577. //row0 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  71578. //row1 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  71579. //tmp1 = shuffle(src0, src1, 2, 3, 6, 7);
  71580. //tmp2 = shuffle(src2, src3, 2, 3, 6, 7);
  71581. //row2 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  71582. //row3 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  71583. // ----
  71584. tmp1 = SIMD.Float32x4.mul(row2, row3);
  71585. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  71586. var minor0 = SIMD.Float32x4.mul(row1, tmp1);
  71587. var minor1 = SIMD.Float32x4.mul(row0, tmp1);
  71588. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  71589. minor0 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row1, tmp1), minor0);
  71590. minor1 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor1);
  71591. minor1 = SIMD.Float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  71592. // ----
  71593. tmp1 = SIMD.Float32x4.mul(row1, row2);
  71594. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  71595. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor0);
  71596. var minor3 = SIMD.Float32x4.mul(row0, tmp1);
  71597. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  71598. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row3, tmp1));
  71599. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor3);
  71600. minor3 = SIMD.Float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  71601. // ----
  71602. tmp1 = SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  71603. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  71604. row2 = SIMD.Float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  71605. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor0);
  71606. var minor2 = SIMD.Float32x4.mul(row0, tmp1);
  71607. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  71608. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row2, tmp1));
  71609. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor2);
  71610. minor2 = SIMD.Float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  71611. // ----
  71612. tmp1 = SIMD.Float32x4.mul(row0, row1);
  71613. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  71614. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor2);
  71615. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row2, tmp1), minor3);
  71616. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  71617. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row3, tmp1), minor2);
  71618. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row2, tmp1));
  71619. // ----
  71620. tmp1 = SIMD.Float32x4.mul(row0, row3);
  71621. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  71622. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row2, tmp1));
  71623. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor2);
  71624. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  71625. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor1);
  71626. minor2 = SIMD.Float32x4.sub(minor2, SIMD.Float32x4.mul(row1, tmp1));
  71627. // ----
  71628. tmp1 = SIMD.Float32x4.mul(row0, row2);
  71629. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  71630. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor1);
  71631. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row1, tmp1));
  71632. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  71633. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row3, tmp1));
  71634. minor3 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor3);
  71635. // Compute determinant
  71636. var det = SIMD.Float32x4.mul(row0, minor0);
  71637. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  71638. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  71639. tmp1 = SIMD.Float32x4.reciprocalApproximation(det);
  71640. det = SIMD.Float32x4.sub(SIMD.Float32x4.add(tmp1, tmp1), SIMD.Float32x4.mul(det, SIMD.Float32x4.mul(tmp1, tmp1)));
  71641. det = SIMD.Float32x4.swizzle(det, 0, 0, 0, 0);
  71642. // These shuffles aren't necessary if the faulty transposition is done
  71643. // up at the top of this function.
  71644. //minor0 =SIMD.Float32x4.swizzle(minor0, 2, 1, 0, 3);
  71645. //minor1 =SIMD.Float32x4.swizzle(minor1, 2, 1, 0, 3);
  71646. //minor2 =SIMD.Float32x4.swizzle(minor2, 2, 1, 0, 3);
  71647. //minor3 =SIMD.Float32x4.swizzle(minor3, 2, 1, 0, 3);
  71648. // Compute final values by multiplying with 1/det
  71649. SIMD.Float32x4.store(dest, 0, SIMD.Float32x4.mul(det, minor0));
  71650. SIMD.Float32x4.store(dest, 4, SIMD.Float32x4.mul(det, minor1));
  71651. SIMD.Float32x4.store(dest, 8, minor2 = SIMD.Float32x4.mul(det, minor2));
  71652. SIMD.Float32x4.store(dest, 12, SIMD.Float32x4.mul(det, minor3));
  71653. return this;
  71654. };
  71655. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  71656. var out = result.m;
  71657. var center = SIMD.Float32x4(targetRef.x, targetRef.y, targetRef.z, 0.0);
  71658. var eye = SIMD.Float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0.0);
  71659. var up = SIMD.Float32x4(upRef.x, upRef.y, upRef.z, 0.0);
  71660. // cc.kmVec3Subtract(f, pCenter, pEye);
  71661. var f = SIMD.Float32x4.sub(center, eye);
  71662. // cc.kmVec3Normalize(f, f);
  71663. var tmp = SIMD.Float32x4.mul(f, f);
  71664. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  71665. f = SIMD.Float32x4.mul(f, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  71666. // cc.kmVec3Assign(up, pUp);
  71667. // cc.kmVec3Normalize(up, up);
  71668. tmp = SIMD.Float32x4.mul(up, up);
  71669. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  71670. up = SIMD.Float32x4.mul(up, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  71671. // cc.kmVec3Cross(s, f, up);
  71672. var s = SIMD.Float32x4.sub(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(f, 1, 2, 0, 3), SIMD.Float32x4.swizzle(up, 2, 0, 1, 3)), SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(f, 2, 0, 1, 3), SIMD.Float32x4.swizzle(up, 1, 2, 0, 3)));
  71673. // cc.kmVec3Normalize(s, s);
  71674. tmp = SIMD.Float32x4.mul(s, s);
  71675. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  71676. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  71677. // cc.kmVec3Cross(u, s, f);
  71678. var u = SIMD.Float32x4.sub(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(s, 1, 2, 0, 3), SIMD.Float32x4.swizzle(f, 2, 0, 1, 3)), SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(s, 2, 0, 1, 3), SIMD.Float32x4.swizzle(f, 1, 2, 0, 3)));
  71679. // cc.kmVec3Normalize(s, s);
  71680. tmp = SIMD.Float32x4.mul(s, s);
  71681. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  71682. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  71683. var zero = SIMD.Float32x4.splat(0.0);
  71684. s = SIMD.Float32x4.neg(s);
  71685. var tmp01 = SIMD.Float32x4.shuffle(s, u, 0, 1, 4, 5);
  71686. var tmp23 = SIMD.Float32x4.shuffle(f, zero, 0, 1, 4, 5);
  71687. var a0 = SIMD.Float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  71688. var a1 = SIMD.Float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  71689. var a2 = SIMD.Float32x4.shuffle(SIMD.Float32x4.shuffle(s, u, 2, 3, 6, 7), SIMD.Float32x4.shuffle(f, zero, 2, 3, 6, 7), 0, 2, 4, 6);
  71690. var a3 = SIMD.Float32x4(0.0, 0.0, 0.0, 1.0);
  71691. var b = SIMD.Float32x4(1.0, 0.0, 0.0, 0.0);
  71692. SIMD.Float32x4.store(out, 0, SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 0, 0, 0, 0), a0), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 1, 1, 1, 1), a1), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 2, 2, 2, 2), a2), SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 3, 3, 3, 3), a3)))));
  71693. b = SIMD.Float32x4(0.0, 1.0, 0.0, 0.0);
  71694. SIMD.Float32x4.store(out, 4, SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 0, 0, 0, 0), a0), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 1, 1, 1, 1), a1), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 2, 2, 2, 2), a2), SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 3, 3, 3, 3), a3)))));
  71695. b = SIMD.Float32x4(0.0, 0.0, 1.0, 0.0);
  71696. SIMD.Float32x4.store(out, 8, SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 0, 0, 0, 0), a0), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 1, 1, 1, 1), a1), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 2, 2, 2, 2), a2), SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 3, 3, 3, 3), a3)))));
  71697. b = SIMD.Float32x4.replaceLane(SIMD.Float32x4.neg(eye), 3, 1.0);
  71698. SIMD.Float32x4.store(out, 12, SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 0, 0, 0, 0), a0), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 1, 1, 1, 1), a1), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 2, 2, 2, 2), a2), SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 3, 3, 3, 3), a3)))));
  71699. };
  71700. return SIMDMatrix;
  71701. }());
  71702. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  71703. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  71704. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  71705. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  71706. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  71707. var SIMDHelper = /** @class */ (function () {
  71708. function SIMDHelper() {
  71709. }
  71710. Object.defineProperty(SIMDHelper, "IsEnabled", {
  71711. get: function () {
  71712. return SIMDHelper._isEnabled;
  71713. },
  71714. enumerable: true,
  71715. configurable: true
  71716. });
  71717. SIMDHelper.DisableSIMD = function () {
  71718. // Replace functions
  71719. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  71720. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  71721. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  71722. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  71723. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  71724. SIMDHelper._isEnabled = false;
  71725. };
  71726. SIMDHelper.EnableSIMD = function () {
  71727. if (self.SIMD === undefined) {
  71728. return;
  71729. }
  71730. // check if polyfills needed
  71731. if (!self.Math.fround) {
  71732. self.Math.fround = (function (array) { return function (x) {
  71733. return array[0] = x, array[0];
  71734. }; })(new Float32Array(1));
  71735. }
  71736. if (!self.Math.imul) {
  71737. self.Math.imul = function (a, b) {
  71738. var ah = (a >>> 16) & 0xffff;
  71739. var al = a & 0xffff;
  71740. var bh = (b >>> 16) & 0xffff;
  71741. var bl = b & 0xffff;
  71742. // the shift by 0 fixes the sign on the high part
  71743. // the final |0 converts the unsigned value into a signed value
  71744. return ((al * bl) + (((ah * bl + al * bh) << 16) >>> 0) | 0);
  71745. };
  71746. }
  71747. // Replace functions
  71748. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  71749. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  71750. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  71751. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  71752. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  71753. SIMDHelper._isEnabled = true;
  71754. };
  71755. SIMDHelper._isEnabled = false;
  71756. return SIMDHelper;
  71757. }());
  71758. BABYLON.SIMDHelper = SIMDHelper;
  71759. })(BABYLON || (BABYLON = {}));
  71760. //# sourceMappingURL=babylon.math.SIMD.js.map
  71761. var BABYLON;
  71762. (function (BABYLON) {
  71763. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  71764. __extends(VRDistortionCorrectionPostProcess, _super);
  71765. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  71766. var _this = _super.call(this, name, "vrDistortionCorrection", [
  71767. 'LensCenter',
  71768. 'Scale',
  71769. 'ScaleIn',
  71770. 'HmdWarpParam'
  71771. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  71772. _this._isRightEye = isRightEye;
  71773. _this._distortionFactors = vrMetrics.distortionK;
  71774. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  71775. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  71776. _this.adaptScaleToCurrentViewport = true;
  71777. _this.onSizeChangedObservable.add(function () {
  71778. _this.aspectRatio = _this.width * .5 / _this.height;
  71779. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  71780. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  71781. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  71782. });
  71783. _this.onApplyObservable.add(function (effect) {
  71784. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  71785. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  71786. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  71787. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  71788. });
  71789. return _this;
  71790. }
  71791. return VRDistortionCorrectionPostProcess;
  71792. }(BABYLON.PostProcess));
  71793. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  71794. })(BABYLON || (BABYLON = {}));
  71795. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  71796. var BABYLON;
  71797. (function (BABYLON) {
  71798. var AnaglyphPostProcess = /** @class */ (function (_super) {
  71799. __extends(AnaglyphPostProcess, _super);
  71800. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  71801. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  71802. _this._passedProcess = rigCameras[0]._rigPostProcess;
  71803. _this.onApplyObservable.add(function (effect) {
  71804. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  71805. });
  71806. return _this;
  71807. }
  71808. return AnaglyphPostProcess;
  71809. }(BABYLON.PostProcess));
  71810. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  71811. })(BABYLON || (BABYLON = {}));
  71812. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  71813. var BABYLON;
  71814. (function (BABYLON) {
  71815. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  71816. __extends(StereoscopicInterlacePostProcess, _super);
  71817. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  71818. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  71819. _this._passedProcess = rigCameras[0]._rigPostProcess;
  71820. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  71821. _this.onSizeChangedObservable.add(function () {
  71822. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  71823. });
  71824. _this.onApplyObservable.add(function (effect) {
  71825. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  71826. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  71827. });
  71828. return _this;
  71829. }
  71830. return StereoscopicInterlacePostProcess;
  71831. }(BABYLON.PostProcess));
  71832. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  71833. })(BABYLON || (BABYLON = {}));
  71834. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  71835. var BABYLON;
  71836. (function (BABYLON) {
  71837. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  71838. function FreeCameraDeviceOrientationInput() {
  71839. var _this = this;
  71840. this._screenOrientationAngle = 0;
  71841. this._screenQuaternion = new BABYLON.Quaternion();
  71842. this._alpha = 0;
  71843. this._beta = 0;
  71844. this._gamma = 0;
  71845. this._orientationChanged = function () {
  71846. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  71847. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  71848. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  71849. };
  71850. this._deviceOrientation = function (evt) {
  71851. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  71852. _this._beta = evt.beta !== null ? evt.beta : 0;
  71853. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  71854. };
  71855. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  71856. this._orientationChanged();
  71857. }
  71858. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  71859. get: function () {
  71860. return this._camera;
  71861. },
  71862. set: function (camera) {
  71863. this._camera = camera;
  71864. if (this._camera != null && !this._camera.rotationQuaternion) {
  71865. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  71866. }
  71867. },
  71868. enumerable: true,
  71869. configurable: true
  71870. });
  71871. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  71872. window.addEventListener("orientationchange", this._orientationChanged);
  71873. window.addEventListener("deviceorientation", this._deviceOrientation);
  71874. //In certain cases, the attach control is called AFTER orientation was changed,
  71875. //So this is needed.
  71876. this._orientationChanged();
  71877. };
  71878. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  71879. window.removeEventListener("orientationchange", this._orientationChanged);
  71880. window.removeEventListener("deviceorientation", this._deviceOrientation);
  71881. };
  71882. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  71883. //if no device orientation provided, don't update the rotation.
  71884. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  71885. if (!this._alpha)
  71886. return;
  71887. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  71888. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  71889. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  71890. //Mirror on XY Plane
  71891. this._camera.rotationQuaternion.z *= -1;
  71892. this._camera.rotationQuaternion.w *= -1;
  71893. };
  71894. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  71895. return "FreeCameraDeviceOrientationInput";
  71896. };
  71897. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  71898. return "deviceOrientation";
  71899. };
  71900. return FreeCameraDeviceOrientationInput;
  71901. }());
  71902. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  71903. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  71904. })(BABYLON || (BABYLON = {}));
  71905. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  71906. var BABYLON;
  71907. (function (BABYLON) {
  71908. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  71909. function ArcRotateCameraVRDeviceOrientationInput() {
  71910. this.alphaCorrection = 1;
  71911. this.betaCorrection = 1;
  71912. this.gammaCorrection = 1;
  71913. this._alpha = 0;
  71914. this._gamma = 0;
  71915. this._dirty = false;
  71916. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  71917. }
  71918. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  71919. this.camera.attachControl(element, noPreventDefault);
  71920. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  71921. };
  71922. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  71923. if (evt.alpha !== null) {
  71924. this._alpha = +evt.alpha | 0;
  71925. }
  71926. if (evt.gamma !== null) {
  71927. this._gamma = +evt.gamma | 0;
  71928. }
  71929. this._dirty = true;
  71930. };
  71931. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  71932. if (this._dirty) {
  71933. this._dirty = false;
  71934. if (this._gamma < 0) {
  71935. this._gamma = 180 + this._gamma;
  71936. }
  71937. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  71938. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  71939. }
  71940. };
  71941. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  71942. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  71943. };
  71944. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  71945. return "ArcRotateCameraVRDeviceOrientationInput";
  71946. };
  71947. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  71948. return "VRDeviceOrientation";
  71949. };
  71950. return ArcRotateCameraVRDeviceOrientationInput;
  71951. }());
  71952. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  71953. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  71954. })(BABYLON || (BABYLON = {}));
  71955. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  71956. var BABYLON;
  71957. (function (BABYLON) {
  71958. var VRCameraMetrics = /** @class */ (function () {
  71959. function VRCameraMetrics() {
  71960. this.compensateDistortion = true;
  71961. }
  71962. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  71963. get: function () {
  71964. return this.hResolution / (2 * this.vResolution);
  71965. },
  71966. enumerable: true,
  71967. configurable: true
  71968. });
  71969. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  71970. get: function () {
  71971. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  71972. },
  71973. enumerable: true,
  71974. configurable: true
  71975. });
  71976. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  71977. get: function () {
  71978. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  71979. var h = (4 * meters) / this.hScreenSize;
  71980. return BABYLON.Matrix.Translation(h, 0, 0);
  71981. },
  71982. enumerable: true,
  71983. configurable: true
  71984. });
  71985. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  71986. get: function () {
  71987. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  71988. var h = (4 * meters) / this.hScreenSize;
  71989. return BABYLON.Matrix.Translation(-h, 0, 0);
  71990. },
  71991. enumerable: true,
  71992. configurable: true
  71993. });
  71994. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  71995. get: function () {
  71996. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  71997. },
  71998. enumerable: true,
  71999. configurable: true
  72000. });
  72001. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  72002. get: function () {
  72003. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  72004. },
  72005. enumerable: true,
  72006. configurable: true
  72007. });
  72008. VRCameraMetrics.GetDefault = function () {
  72009. var result = new VRCameraMetrics();
  72010. result.hResolution = 1280;
  72011. result.vResolution = 800;
  72012. result.hScreenSize = 0.149759993;
  72013. result.vScreenSize = 0.0935999975;
  72014. result.vScreenCenter = 0.0467999987;
  72015. result.eyeToScreenDistance = 0.0410000011;
  72016. result.lensSeparationDistance = 0.0635000020;
  72017. result.interpupillaryDistance = 0.0640000030;
  72018. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  72019. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  72020. result.postProcessScaleFactor = 1.714605507808412;
  72021. result.lensCenterOffset = 0.151976421;
  72022. return result;
  72023. };
  72024. return VRCameraMetrics;
  72025. }());
  72026. BABYLON.VRCameraMetrics = VRCameraMetrics;
  72027. })(BABYLON || (BABYLON = {}));
  72028. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  72029. var BABYLON;
  72030. (function (BABYLON) {
  72031. var WebVRFreeCamera = /** @class */ (function (_super) {
  72032. __extends(WebVRFreeCamera, _super);
  72033. function WebVRFreeCamera(name, position, scene, webVROptions) {
  72034. if (webVROptions === void 0) { webVROptions = {}; }
  72035. var _this = _super.call(this, name, position, scene) || this;
  72036. _this.webVROptions = webVROptions;
  72037. _this._vrDevice = null;
  72038. _this.rawPose = null;
  72039. _this._specsVersion = "1.1";
  72040. _this._attached = false;
  72041. _this._descendants = [];
  72042. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  72043. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  72044. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  72045. _this._standingMatrix = null;
  72046. // Represents device position and rotation in babylon space
  72047. _this.devicePosition = BABYLON.Vector3.Zero();
  72048. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  72049. _this.deviceScaleFactor = 1;
  72050. _this._deviceToWorld = BABYLON.Matrix.Identity();
  72051. _this._worldToDevice = BABYLON.Matrix.Identity();
  72052. _this.controllers = [];
  72053. _this.onControllersAttachedObservable = new BABYLON.Observable();
  72054. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  72055. _this.rigParenting = true; // should the rig cameras be used as parent instead of this camera.
  72056. _this._defaultHeight = 0;
  72057. _this.deviceDistanceToRoomGround = function () {
  72058. if (_this._standingMatrix) {
  72059. // Add standing matrix offset to get real offset from ground in room
  72060. _this._standingMatrix.getTranslationToRef(_this._workingVector);
  72061. return _this._deviceRoomPosition.y + _this._workingVector.y;
  72062. }
  72063. else {
  72064. return _this._defaultHeight;
  72065. }
  72066. };
  72067. _this.useStandingMatrix = function (callback) {
  72068. if (callback === void 0) { callback = function (bool) { }; }
  72069. // Use standing matrix if availible
  72070. if (!navigator || !navigator.getVRDisplays) {
  72071. callback(false);
  72072. }
  72073. else {
  72074. navigator.getVRDisplays().then(function (displays) {
  72075. if (!displays || !displays[0] || !displays[0].stageParameters || !displays[0].stageParameters.sittingToStandingTransform) {
  72076. callback(false);
  72077. }
  72078. else {
  72079. _this._standingMatrix = new BABYLON.Matrix();
  72080. BABYLON.Matrix.FromFloat32ArrayToRefScaled(displays[0].stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  72081. if (!_this.getScene().useRightHandedSystem) {
  72082. [2, 6, 8, 9, 14].forEach(function (num) {
  72083. if (_this._standingMatrix) {
  72084. _this._standingMatrix.m[num] *= -1;
  72085. }
  72086. });
  72087. }
  72088. callback(true);
  72089. }
  72090. });
  72091. }
  72092. };
  72093. _this._workingVector = BABYLON.Vector3.Zero();
  72094. _this._oneVector = BABYLON.Vector3.One();
  72095. _this._workingMatrix = BABYLON.Matrix.Identity();
  72096. _this._cache.position = BABYLON.Vector3.Zero();
  72097. if (webVROptions.defaultHeight) {
  72098. _this._defaultHeight = webVROptions.defaultHeight;
  72099. _this.position.y = _this._defaultHeight;
  72100. }
  72101. _this.minZ = 0.1;
  72102. //legacy support - the compensation boolean was removed.
  72103. if (arguments.length === 5) {
  72104. _this.webVROptions = arguments[4];
  72105. }
  72106. // default webVR options
  72107. if (_this.webVROptions.trackPosition == undefined) {
  72108. _this.webVROptions.trackPosition = true;
  72109. }
  72110. if (_this.webVROptions.controllerMeshes == undefined) {
  72111. _this.webVROptions.controllerMeshes = true;
  72112. }
  72113. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  72114. _this.webVROptions.defaultLightingOnControllers = true;
  72115. }
  72116. _this.rotationQuaternion = new BABYLON.Quaternion();
  72117. if (_this.webVROptions && _this.webVROptions.positionScale) {
  72118. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  72119. }
  72120. //enable VR
  72121. var engine = _this.getEngine();
  72122. _this._onVREnabled = function (success) { if (success) {
  72123. _this.initControllers();
  72124. } };
  72125. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  72126. engine.initWebVR().add(function (event) {
  72127. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  72128. return;
  72129. }
  72130. _this._vrDevice = event.vrDisplay;
  72131. //reset the rig parameters.
  72132. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  72133. if (_this._attached) {
  72134. _this.getEngine().enableVR();
  72135. }
  72136. });
  72137. if (typeof (VRFrameData) !== "undefined")
  72138. _this._frameData = new VRFrameData();
  72139. /**
  72140. * The idea behind the following lines:
  72141. * objects that have the camera as parent should actually have the rig cameras as a parent.
  72142. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  72143. * the second will not show it correctly.
  72144. *
  72145. * To solve this - each object that has the camera as parent will be added to a protected array.
  72146. * When the rig camera renders, it will take this array and set all of those to be its children.
  72147. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  72148. * Amazing!
  72149. */
  72150. scene.onBeforeCameraRenderObservable.add(function (camera) {
  72151. if (camera.parent === _this && _this.rigParenting) {
  72152. _this._descendants = _this.getDescendants(true, function (n) {
  72153. // don't take the cameras or the controllers!
  72154. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  72155. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  72156. return !isController && !isRigCamera;
  72157. });
  72158. _this._descendants.forEach(function (node) {
  72159. node.parent = camera;
  72160. });
  72161. }
  72162. });
  72163. scene.onAfterCameraRenderObservable.add(function (camera) {
  72164. if (camera.parent === _this && _this.rigParenting) {
  72165. _this._descendants.forEach(function (node) {
  72166. node.parent = _this;
  72167. });
  72168. }
  72169. });
  72170. return _this;
  72171. }
  72172. WebVRFreeCamera.prototype.dispose = function () {
  72173. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  72174. _super.prototype.dispose.call(this);
  72175. };
  72176. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  72177. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  72178. var gp = _a[_i];
  72179. if (gp.hand === name) {
  72180. return gp;
  72181. }
  72182. }
  72183. return null;
  72184. };
  72185. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  72186. get: function () {
  72187. if (!this._leftController) {
  72188. this._leftController = this.getControllerByName("left");
  72189. }
  72190. return this._leftController;
  72191. },
  72192. enumerable: true,
  72193. configurable: true
  72194. });
  72195. ;
  72196. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  72197. get: function () {
  72198. if (!this._rightController) {
  72199. this._rightController = this.getControllerByName("right");
  72200. }
  72201. return this._rightController;
  72202. },
  72203. enumerable: true,
  72204. configurable: true
  72205. });
  72206. ;
  72207. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  72208. if (length === void 0) { length = 100; }
  72209. if (this.leftCamera) {
  72210. // Use left eye to avoid computation to compute center on every call
  72211. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  72212. }
  72213. else {
  72214. return _super.prototype.getForwardRay.call(this, length);
  72215. }
  72216. };
  72217. WebVRFreeCamera.prototype._checkInputs = function () {
  72218. if (this._vrDevice && this._vrDevice.isPresenting) {
  72219. this._vrDevice.getFrameData(this._frameData);
  72220. this.updateFromDevice(this._frameData.pose);
  72221. }
  72222. _super.prototype._checkInputs.call(this);
  72223. };
  72224. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  72225. if (poseData && poseData.orientation) {
  72226. this.rawPose = poseData;
  72227. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  72228. if (this.getScene().useRightHandedSystem) {
  72229. this._deviceRoomRotationQuaternion.z *= -1;
  72230. this._deviceRoomRotationQuaternion.w *= -1;
  72231. }
  72232. if (this.webVROptions.trackPosition && this.rawPose.position) {
  72233. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  72234. if (this.getScene().useRightHandedSystem) {
  72235. this._deviceRoomPosition.z *= -1;
  72236. }
  72237. }
  72238. }
  72239. };
  72240. /**
  72241. * WebVR's attach control will start broadcasting frames to the device.
  72242. * Note that in certain browsers (chrome for example) this function must be called
  72243. * within a user-interaction callback. Example:
  72244. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  72245. *
  72246. * @param {HTMLElement} element
  72247. * @param {boolean} [noPreventDefault]
  72248. *
  72249. * @memberOf WebVRFreeCamera
  72250. */
  72251. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  72252. _super.prototype.attachControl.call(this, element, noPreventDefault);
  72253. this._attached = true;
  72254. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  72255. if (this._vrDevice) {
  72256. this.getEngine().enableVR();
  72257. }
  72258. };
  72259. WebVRFreeCamera.prototype.detachControl = function (element) {
  72260. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  72261. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  72262. _super.prototype.detachControl.call(this, element);
  72263. this._attached = false;
  72264. this.getEngine().disableVR();
  72265. };
  72266. WebVRFreeCamera.prototype.getClassName = function () {
  72267. return "WebVRFreeCamera";
  72268. };
  72269. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  72270. //uses the vrDisplay's "resetPose()".
  72271. //pitch and roll won't be affected.
  72272. this._vrDevice.resetPose();
  72273. };
  72274. WebVRFreeCamera.prototype._updateRigCameras = function () {
  72275. var camLeft = this._rigCameras[0];
  72276. var camRight = this._rigCameras[1];
  72277. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  72278. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  72279. camLeft.position.copyFrom(this._deviceRoomPosition);
  72280. camRight.position.copyFrom(this._deviceRoomPosition);
  72281. };
  72282. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  72283. var _this = this;
  72284. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  72285. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  72286. if (!this.updateCacheCalled) {
  72287. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  72288. this.updateCacheCalled = true;
  72289. this.update();
  72290. }
  72291. // Set working vector to the device position in room space rotated by the new rotation
  72292. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  72293. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  72294. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  72295. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  72296. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  72297. // Add translation from anchor position
  72298. this._deviceToWorld.getTranslationToRef(this._workingVector);
  72299. this._workingVector.addInPlace(this.position);
  72300. this._workingVector.subtractInPlace(this._cache.position);
  72301. this._deviceToWorld.setTranslation(this._workingVector);
  72302. // Set an inverted matrix to be used when updating the camera
  72303. this._deviceToWorld.invertToRef(this._worldToDevice);
  72304. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  72305. this.controllers.forEach(function (controller) {
  72306. controller._deviceToWorld = _this._deviceToWorld;
  72307. controller.update();
  72308. });
  72309. }
  72310. if (!ignoreParentClass) {
  72311. _super.prototype._updateCache.call(this);
  72312. }
  72313. this.updateCacheCalled = false;
  72314. };
  72315. WebVRFreeCamera.prototype.update = function () {
  72316. // Get current device position in babylon world
  72317. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  72318. // Get current device rotation in babylon world
  72319. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  72320. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  72321. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  72322. _super.prototype.update.call(this);
  72323. };
  72324. WebVRFreeCamera.prototype._getViewMatrix = function () {
  72325. return BABYLON.Matrix.Identity();
  72326. };
  72327. /**
  72328. * This function is called by the two RIG cameras.
  72329. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  72330. */
  72331. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  72332. var _this = this;
  72333. //WebVR 1.1
  72334. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  72335. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  72336. if (!this.getScene().useRightHandedSystem) {
  72337. [2, 6, 8, 9, 14].forEach(function (num) {
  72338. _this._webvrViewMatrix.m[num] *= -1;
  72339. });
  72340. }
  72341. // update the camera rotation matrix
  72342. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  72343. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  72344. // Computing target and final matrix
  72345. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  72346. var parentCamera = this._cameraRigParams["parentCamera"];
  72347. // should the view matrix be updated with scale and position offset?
  72348. if (parentCamera.deviceScaleFactor !== 1) {
  72349. this._webvrViewMatrix.invert();
  72350. // scale the position, if set
  72351. if (parentCamera.deviceScaleFactor) {
  72352. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  72353. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  72354. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  72355. }
  72356. this._webvrViewMatrix.invert();
  72357. }
  72358. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  72359. return this._webvrViewMatrix;
  72360. };
  72361. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  72362. var _this = this;
  72363. var parentCamera = this.parent;
  72364. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  72365. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  72366. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  72367. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  72368. //babylon compatible matrix
  72369. if (!this.getScene().useRightHandedSystem) {
  72370. [8, 9, 10, 11].forEach(function (num) {
  72371. _this._projectionMatrix.m[num] *= -1;
  72372. });
  72373. }
  72374. return this._projectionMatrix;
  72375. };
  72376. WebVRFreeCamera.prototype.initControllers = function () {
  72377. var _this = this;
  72378. this.controllers = [];
  72379. var manager = this.getScene().gamepadManager;
  72380. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  72381. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  72382. var webVrController = gamepad;
  72383. if (webVrController.defaultModel) {
  72384. webVrController.defaultModel.setEnabled(false);
  72385. }
  72386. if (webVrController.hand === "right") {
  72387. _this._rightController = null;
  72388. }
  72389. if (webVrController.hand === "left") {
  72390. _this._rightController = null;
  72391. }
  72392. var controllerIndex = _this.controllers.indexOf(webVrController);
  72393. if (controllerIndex !== -1) {
  72394. _this.controllers.splice(controllerIndex, 1);
  72395. }
  72396. }
  72397. });
  72398. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  72399. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  72400. var webVrController_1 = gamepad;
  72401. webVrController_1._deviceToWorld = _this._deviceToWorld;
  72402. if (_this.webVROptions.controllerMeshes) {
  72403. if (webVrController_1.defaultModel) {
  72404. webVrController_1.defaultModel.setEnabled(true);
  72405. }
  72406. else {
  72407. // Load the meshes
  72408. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  72409. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  72410. if (_this.webVROptions.defaultLightingOnControllers) {
  72411. if (!_this._lightOnControllers) {
  72412. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  72413. }
  72414. var activateLightOnSubMeshes_1 = function (mesh, light) {
  72415. var children = mesh.getChildren();
  72416. if (children.length !== 0) {
  72417. children.forEach(function (mesh) {
  72418. light.includedOnlyMeshes.push(mesh);
  72419. activateLightOnSubMeshes_1(mesh, light);
  72420. });
  72421. }
  72422. };
  72423. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  72424. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  72425. }
  72426. });
  72427. }
  72428. }
  72429. webVrController_1.attachToPoseControlledCamera(_this);
  72430. // since this is async - sanity check. Is the controller already stored?
  72431. if (_this.controllers.indexOf(webVrController_1) === -1) {
  72432. //add to the controllers array
  72433. _this.controllers.push(webVrController_1);
  72434. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  72435. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  72436. // So we're overriding setting left & right manually to be sure
  72437. var firstViveWandDetected = false;
  72438. for (var i = 0; i < _this.controllers.length; i++) {
  72439. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  72440. if (!firstViveWandDetected) {
  72441. firstViveWandDetected = true;
  72442. _this.controllers[i].hand = "left";
  72443. }
  72444. else {
  72445. _this.controllers[i].hand = "right";
  72446. }
  72447. }
  72448. }
  72449. //did we find enough controllers? Great! let the developer know.
  72450. if (_this.controllers.length >= 2) {
  72451. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  72452. }
  72453. }
  72454. }
  72455. });
  72456. };
  72457. return WebVRFreeCamera;
  72458. }(BABYLON.FreeCamera));
  72459. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  72460. })(BABYLON || (BABYLON = {}));
  72461. //# sourceMappingURL=babylon.webVRCamera.js.map
  72462. var BABYLON;
  72463. (function (BABYLON) {
  72464. // We're mainly based on the logic defined into the FreeCamera code
  72465. var DeviceOrientationCamera = /** @class */ (function (_super) {
  72466. __extends(DeviceOrientationCamera, _super);
  72467. function DeviceOrientationCamera(name, position, scene) {
  72468. var _this = _super.call(this, name, position, scene) || this;
  72469. _this._quaternionCache = new BABYLON.Quaternion();
  72470. _this.inputs.addDeviceOrientation();
  72471. return _this;
  72472. }
  72473. DeviceOrientationCamera.prototype.getClassName = function () {
  72474. return "DeviceOrientationCamera";
  72475. };
  72476. DeviceOrientationCamera.prototype._checkInputs = function () {
  72477. _super.prototype._checkInputs.call(this);
  72478. this._quaternionCache.copyFrom(this.rotationQuaternion);
  72479. if (this._initialQuaternion) {
  72480. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  72481. }
  72482. };
  72483. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  72484. var _this = this;
  72485. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  72486. //can only work if this camera has a rotation quaternion already.
  72487. if (!this.rotationQuaternion)
  72488. return;
  72489. if (!this._initialQuaternion) {
  72490. this._initialQuaternion = new BABYLON.Quaternion();
  72491. }
  72492. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  72493. ['x', 'y', 'z'].forEach(function (axisName) {
  72494. if (!axis[axisName]) {
  72495. _this._initialQuaternion[axisName] = 0;
  72496. }
  72497. else {
  72498. _this._initialQuaternion[axisName] *= -1;
  72499. }
  72500. });
  72501. this._initialQuaternion.normalize();
  72502. //force rotation update
  72503. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  72504. };
  72505. return DeviceOrientationCamera;
  72506. }(BABYLON.FreeCamera));
  72507. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  72508. })(BABYLON || (BABYLON = {}));
  72509. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  72510. var BABYLON;
  72511. (function (BABYLON) {
  72512. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  72513. __extends(VRDeviceOrientationFreeCamera, _super);
  72514. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  72515. if (compensateDistortion === void 0) { compensateDistortion = true; }
  72516. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  72517. var _this = _super.call(this, name, position, scene) || this;
  72518. vrCameraMetrics.compensateDistortion = compensateDistortion;
  72519. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  72520. return _this;
  72521. }
  72522. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  72523. return "VRDeviceOrientationFreeCamera";
  72524. };
  72525. return VRDeviceOrientationFreeCamera;
  72526. }(BABYLON.DeviceOrientationCamera));
  72527. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  72528. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  72529. __extends(VRDeviceOrientationGamepadCamera, _super);
  72530. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  72531. if (compensateDistortion === void 0) { compensateDistortion = true; }
  72532. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  72533. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  72534. _this.inputs.addGamepad();
  72535. return _this;
  72536. }
  72537. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  72538. return "VRDeviceOrientationGamepadCamera";
  72539. };
  72540. return VRDeviceOrientationGamepadCamera;
  72541. }(VRDeviceOrientationFreeCamera));
  72542. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  72543. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  72544. __extends(VRDeviceOrientationArcRotateCamera, _super);
  72545. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  72546. if (compensateDistortion === void 0) { compensateDistortion = true; }
  72547. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  72548. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  72549. vrCameraMetrics.compensateDistortion = compensateDistortion;
  72550. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  72551. _this.inputs.addVRDeviceOrientation();
  72552. return _this;
  72553. }
  72554. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  72555. return "VRDeviceOrientationArcRotateCamera";
  72556. };
  72557. return VRDeviceOrientationArcRotateCamera;
  72558. }(BABYLON.ArcRotateCamera));
  72559. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  72560. })(BABYLON || (BABYLON = {}));
  72561. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  72562. var BABYLON;
  72563. (function (BABYLON) {
  72564. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  72565. __extends(AnaglyphFreeCamera, _super);
  72566. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  72567. var _this = _super.call(this, name, position, scene) || this;
  72568. _this.interaxialDistance = interaxialDistance;
  72569. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  72570. return _this;
  72571. }
  72572. AnaglyphFreeCamera.prototype.getClassName = function () {
  72573. return "AnaglyphFreeCamera";
  72574. };
  72575. return AnaglyphFreeCamera;
  72576. }(BABYLON.FreeCamera));
  72577. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  72578. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  72579. __extends(AnaglyphArcRotateCamera, _super);
  72580. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  72581. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  72582. _this.interaxialDistance = interaxialDistance;
  72583. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  72584. return _this;
  72585. }
  72586. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  72587. return "AnaglyphArcRotateCamera";
  72588. };
  72589. return AnaglyphArcRotateCamera;
  72590. }(BABYLON.ArcRotateCamera));
  72591. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  72592. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  72593. __extends(AnaglyphGamepadCamera, _super);
  72594. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  72595. var _this = _super.call(this, name, position, scene) || this;
  72596. _this.interaxialDistance = interaxialDistance;
  72597. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  72598. return _this;
  72599. }
  72600. AnaglyphGamepadCamera.prototype.getClassName = function () {
  72601. return "AnaglyphGamepadCamera";
  72602. };
  72603. return AnaglyphGamepadCamera;
  72604. }(BABYLON.GamepadCamera));
  72605. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  72606. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  72607. __extends(AnaglyphUniversalCamera, _super);
  72608. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  72609. var _this = _super.call(this, name, position, scene) || this;
  72610. _this.interaxialDistance = interaxialDistance;
  72611. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  72612. return _this;
  72613. }
  72614. AnaglyphUniversalCamera.prototype.getClassName = function () {
  72615. return "AnaglyphUniversalCamera";
  72616. };
  72617. return AnaglyphUniversalCamera;
  72618. }(BABYLON.UniversalCamera));
  72619. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  72620. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  72621. __extends(StereoscopicFreeCamera, _super);
  72622. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  72623. var _this = _super.call(this, name, position, scene) || this;
  72624. _this.interaxialDistance = interaxialDistance;
  72625. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  72626. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  72627. return _this;
  72628. }
  72629. StereoscopicFreeCamera.prototype.getClassName = function () {
  72630. return "StereoscopicFreeCamera";
  72631. };
  72632. return StereoscopicFreeCamera;
  72633. }(BABYLON.FreeCamera));
  72634. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  72635. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  72636. __extends(StereoscopicArcRotateCamera, _super);
  72637. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  72638. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  72639. _this.interaxialDistance = interaxialDistance;
  72640. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  72641. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  72642. return _this;
  72643. }
  72644. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  72645. return "StereoscopicArcRotateCamera";
  72646. };
  72647. return StereoscopicArcRotateCamera;
  72648. }(BABYLON.ArcRotateCamera));
  72649. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  72650. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  72651. __extends(StereoscopicGamepadCamera, _super);
  72652. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  72653. var _this = _super.call(this, name, position, scene) || this;
  72654. _this.interaxialDistance = interaxialDistance;
  72655. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  72656. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  72657. return _this;
  72658. }
  72659. StereoscopicGamepadCamera.prototype.getClassName = function () {
  72660. return "StereoscopicGamepadCamera";
  72661. };
  72662. return StereoscopicGamepadCamera;
  72663. }(BABYLON.GamepadCamera));
  72664. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  72665. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  72666. __extends(StereoscopicUniversalCamera, _super);
  72667. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  72668. var _this = _super.call(this, name, position, scene) || this;
  72669. _this.interaxialDistance = interaxialDistance;
  72670. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  72671. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  72672. return _this;
  72673. }
  72674. StereoscopicUniversalCamera.prototype.getClassName = function () {
  72675. return "StereoscopicUniversalCamera";
  72676. };
  72677. return StereoscopicUniversalCamera;
  72678. }(BABYLON.UniversalCamera));
  72679. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  72680. })(BABYLON || (BABYLON = {}));
  72681. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  72682. var BABYLON;
  72683. (function (BABYLON) {
  72684. var VRExperienceHelper = /** @class */ (function () {
  72685. function VRExperienceHelper(scene, webVROptions) {
  72686. if (webVROptions === void 0) { webVROptions = {}; }
  72687. var _this = this;
  72688. this.webVROptions = webVROptions;
  72689. // Can the system support WebVR, even if a headset isn't plugged in?
  72690. this._webVRsupported = false;
  72691. // If WebVR is supported, is a headset plugged in and are we ready to present?
  72692. this._webVRready = false;
  72693. // Are we waiting for the requestPresent callback to complete?
  72694. this._webVRrequesting = false;
  72695. // Are we presenting to the headset right now?
  72696. this._webVRpresenting = false;
  72697. // Are we presenting in the fullscreen fallback?
  72698. this._fullscreenVRpresenting = false;
  72699. /**
  72700. * Observable raised when entering VR.
  72701. */
  72702. this.onEnteringVRObservable = new BABYLON.Observable();
  72703. /**
  72704. * Observable raised when exiting VR.
  72705. */
  72706. this.onExitingVRObservable = new BABYLON.Observable();
  72707. /**
  72708. * Observable raised when controller mesh is loaded.
  72709. */
  72710. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  72711. this._useCustomVRButton = false;
  72712. this._teleportationRequested = false;
  72713. this._teleportationEnabledOnLeftController = false;
  72714. this._teleportationEnabledOnRightController = false;
  72715. this._interactionsEnabledOnLeftController = false;
  72716. this._interactionsEnabledOnRightController = false;
  72717. this._leftControllerReady = false;
  72718. this._rightControllerReady = false;
  72719. this._floorMeshesCollection = [];
  72720. this._teleportationAllowed = false;
  72721. this._rotationAllowed = true;
  72722. this._teleportationRequestInitiated = false;
  72723. this._teleportationBackRequestInitiated = false;
  72724. this.teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  72725. this._rotationRightAsked = false;
  72726. this._rotationLeftAsked = false;
  72727. this._isDefaultTeleportationTarget = true;
  72728. this._teleportationFillColor = "#444444";
  72729. this._teleportationBorderColor = "#FFFFFF";
  72730. this._rotationAngle = 0;
  72731. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  72732. this._padSensibilityUp = 0.65;
  72733. this._padSensibilityDown = 0.35;
  72734. this.onNewMeshSelected = new BABYLON.Observable();
  72735. /**
  72736. * Observable raised when current selected mesh gets unselected
  72737. */
  72738. this.onSelectedMeshUnselected = new BABYLON.Observable();
  72739. this._pointerDownOnMeshAsked = false;
  72740. this._isActionableMesh = false;
  72741. this._teleportationEnabled = false;
  72742. this._interactionsEnabled = false;
  72743. this._interactionsRequested = false;
  72744. this._displayGaze = true;
  72745. this._displayLaserPointer = true;
  72746. this._dpadPressed = true;
  72747. this._onResize = function () {
  72748. _this.moveButtonToBottomRight();
  72749. if (_this._fullscreenVRpresenting && _this._webVRready) {
  72750. _this.exitVR();
  72751. }
  72752. };
  72753. this._onFullscreenChange = function () {
  72754. if (document.fullscreen !== undefined) {
  72755. _this._fullscreenVRpresenting = document.fullscreen;
  72756. }
  72757. else if (document.mozFullScreen !== undefined) {
  72758. _this._fullscreenVRpresenting = document.mozFullScreen;
  72759. }
  72760. else if (document.webkitIsFullScreen !== undefined) {
  72761. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  72762. }
  72763. else if (document.msIsFullScreen !== undefined) {
  72764. _this._fullscreenVRpresenting = document.msIsFullScreen;
  72765. }
  72766. if (!_this._fullscreenVRpresenting && _this._canvas) {
  72767. _this.exitVR();
  72768. if (!_this._useCustomVRButton) {
  72769. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  72770. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  72771. }
  72772. }
  72773. };
  72774. this.beforeRender = function () {
  72775. _this._castRayAndSelectObject();
  72776. };
  72777. this._onNewGamepadConnected = function (gamepad) {
  72778. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  72779. if (gamepad.leftStick) {
  72780. gamepad.onleftstickchanged(function (stickValues) {
  72781. if (_this._teleportationEnabled) {
  72782. // Listening to classic/xbox gamepad only if no VR controller is active
  72783. if ((!_this._leftLaserPointer && !_this._rightLaserPointer) ||
  72784. ((_this._leftLaserPointer && !_this._leftLaserPointer.isVisible) &&
  72785. (_this._rightLaserPointer && !_this._rightLaserPointer.isVisible))) {
  72786. _this._checkTeleportWithRay(stickValues);
  72787. _this._checkTeleportBackwards(stickValues);
  72788. }
  72789. }
  72790. });
  72791. }
  72792. if (gamepad.rightStick) {
  72793. gamepad.onrightstickchanged(function (stickValues) {
  72794. if (_this._teleportationEnabled) {
  72795. _this._checkRotate(stickValues);
  72796. }
  72797. });
  72798. }
  72799. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  72800. gamepad.onbuttondown(function (buttonPressed) {
  72801. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  72802. _this._selectionPointerDown();
  72803. }
  72804. });
  72805. gamepad.onbuttonup(function (buttonPressed) {
  72806. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  72807. _this._selectionPointerUp();
  72808. }
  72809. });
  72810. }
  72811. }
  72812. else {
  72813. var webVRController = gamepad;
  72814. _this._tryEnableInteractionOnController(webVRController);
  72815. }
  72816. };
  72817. // 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
  72818. this._tryEnableInteractionOnController = function (webVRController) {
  72819. if (webVRController.hand === "left") {
  72820. _this._leftControllerReady = true;
  72821. if (_this._interactionsRequested && !_this._interactionsEnabledOnLeftController) {
  72822. _this._enableInteractionOnController(webVRController);
  72823. }
  72824. if (_this._teleportationRequested && !_this._teleportationEnabledOnLeftController) {
  72825. _this._enableTeleportationOnController(webVRController);
  72826. }
  72827. }
  72828. if (webVRController.hand === "right") {
  72829. _this._rightControllerReady = true;
  72830. if (_this._interactionsRequested && !_this._interactionsEnabledOnRightController) {
  72831. _this._enableInteractionOnController(webVRController);
  72832. }
  72833. if (_this._teleportationRequested && !_this._teleportationEnabledOnRightController) {
  72834. _this._enableTeleportationOnController(webVRController);
  72835. }
  72836. }
  72837. };
  72838. this._onNewGamepadDisconnected = function (gamepad) {
  72839. if (gamepad instanceof BABYLON.WebVRController) {
  72840. if (gamepad.hand === "left") {
  72841. _this._interactionsEnabledOnLeftController = false;
  72842. _this._teleportationEnabledOnLeftController = false;
  72843. _this._leftControllerReady = false;
  72844. if (_this._leftLaserPointer) {
  72845. _this._leftLaserPointer.dispose();
  72846. }
  72847. }
  72848. if (gamepad.hand === "right") {
  72849. _this._interactionsEnabledOnRightController = false;
  72850. _this._teleportationEnabledOnRightController = false;
  72851. _this._rightControllerReady = false;
  72852. if (_this._rightLaserPointer) {
  72853. _this._rightLaserPointer.dispose();
  72854. }
  72855. }
  72856. }
  72857. };
  72858. this._workingVector = BABYLON.Vector3.Zero();
  72859. this._workingQuaternion = BABYLON.Quaternion.Identity();
  72860. this._workingMatrix = BABYLON.Matrix.Identity();
  72861. this._scene = scene;
  72862. this._canvas = scene.getEngine().getRenderingCanvas();
  72863. // Parse options
  72864. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  72865. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  72866. }
  72867. if (webVROptions.createDeviceOrientationCamera === undefined) {
  72868. webVROptions.createDeviceOrientationCamera = true;
  72869. }
  72870. if (webVROptions.defaultHeight === undefined) {
  72871. webVROptions.defaultHeight = 1.7;
  72872. }
  72873. if (webVROptions.useCustomVRButton) {
  72874. this._useCustomVRButton = true;
  72875. if (webVROptions.customVRButton) {
  72876. this._btnVR = webVROptions.customVRButton;
  72877. }
  72878. }
  72879. if (webVROptions.rayLength) {
  72880. this._rayLength = webVROptions.rayLength;
  72881. }
  72882. this._defaultHeight = webVROptions.defaultHeight;
  72883. // Set position
  72884. if (this._scene.activeCamera) {
  72885. this._position = this._scene.activeCamera.position.clone();
  72886. }
  72887. else {
  72888. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  72889. }
  72890. // Set non-vr camera
  72891. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  72892. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  72893. // Copy data from existing camera
  72894. if (this._scene.activeCamera) {
  72895. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  72896. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  72897. // Set rotation from previous camera
  72898. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  72899. var targetCamera = this._scene.activeCamera;
  72900. if (targetCamera.rotationQuaternion) {
  72901. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  72902. }
  72903. else {
  72904. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  72905. }
  72906. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  72907. }
  72908. }
  72909. this._scene.activeCamera = this._deviceOrientationCamera;
  72910. if (this._canvas) {
  72911. this._scene.activeCamera.attachControl(this._canvas);
  72912. }
  72913. }
  72914. else {
  72915. this._existingCamera = this._scene.activeCamera;
  72916. }
  72917. // Create VR cameras
  72918. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  72919. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  72920. }
  72921. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  72922. this._webVRCamera.useStandingMatrix();
  72923. // Create default button
  72924. if (!this._useCustomVRButton) {
  72925. this._btnVR = document.createElement("BUTTON");
  72926. this._btnVR.className = "babylonVRicon";
  72927. this._btnVR.id = "babylonVRiconbtn";
  72928. this._btnVR.title = "Click to switch to VR";
  72929. 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) }";
  72930. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  72931. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  72932. // css += ".babylonVRicon.vrdisplaysupported { }";
  72933. // css += ".babylonVRicon.vrdisplayready { }";
  72934. // css += ".babylonVRicon.vrdisplayrequesting { }";
  72935. var style = document.createElement('style');
  72936. style.appendChild(document.createTextNode(css));
  72937. document.getElementsByTagName('head')[0].appendChild(style);
  72938. this.moveButtonToBottomRight();
  72939. }
  72940. // VR button click event
  72941. if (this._btnVR) {
  72942. this._btnVR.addEventListener("click", function () {
  72943. if (!_this.isInVRMode) {
  72944. _this.enterVR();
  72945. }
  72946. else {
  72947. _this.exitVR();
  72948. }
  72949. });
  72950. }
  72951. // Window events
  72952. window.addEventListener("resize", this._onResize);
  72953. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  72954. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  72955. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  72956. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  72957. // Display vr button when headset is connected
  72958. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  72959. this.displayVRButton();
  72960. }
  72961. else {
  72962. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  72963. if (e.vrDisplay) {
  72964. _this.displayVRButton();
  72965. }
  72966. });
  72967. }
  72968. // Exiting VR mode using 'ESC' key on desktop
  72969. this._onKeyDown = function (event) {
  72970. if (event.keyCode === 27 && _this.isInVRMode) {
  72971. _this.exitVR();
  72972. }
  72973. };
  72974. document.addEventListener("keydown", this._onKeyDown);
  72975. // Exiting VR mode double tapping the touch screen
  72976. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  72977. if (_this.isInVRMode) {
  72978. _this.exitVR();
  72979. if (_this._fullscreenVRpresenting) {
  72980. _this._scene.getEngine().switchFullscreen(true);
  72981. }
  72982. }
  72983. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  72984. // Listen for WebVR display changes
  72985. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  72986. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  72987. this._onVRRequestPresentStart = function () {
  72988. _this._webVRrequesting = true;
  72989. _this.updateButtonVisibility();
  72990. };
  72991. this._onVRRequestPresentComplete = function (success) {
  72992. _this._webVRrequesting = false;
  72993. _this.updateButtonVisibility();
  72994. };
  72995. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  72996. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  72997. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  72998. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  72999. scene.onDisposeObservable.add(function () {
  73000. _this.dispose();
  73001. });
  73002. // Gamepad connection events
  73003. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  73004. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  73005. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  73006. this.updateButtonVisibility();
  73007. //create easing functions
  73008. this._circleEase = new BABYLON.CircleEase();
  73009. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  73010. }
  73011. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  73012. /** Return this.onEnteringVRObservable
  73013. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  73014. */
  73015. get: function () {
  73016. return this.onEnteringVRObservable;
  73017. },
  73018. enumerable: true,
  73019. configurable: true
  73020. });
  73021. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  73022. /** Return this.onExitingVRObservable
  73023. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  73024. */
  73025. get: function () {
  73026. return this.onExitingVRObservable;
  73027. },
  73028. enumerable: true,
  73029. configurable: true
  73030. });
  73031. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  73032. /** Return this.onControllerMeshLoadedObservable
  73033. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  73034. */
  73035. get: function () {
  73036. return this.onControllerMeshLoadedObservable;
  73037. },
  73038. enumerable: true,
  73039. configurable: true
  73040. });
  73041. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  73042. get: function () {
  73043. return this._teleportationTarget;
  73044. },
  73045. set: function (value) {
  73046. if (value) {
  73047. value.name = "teleportationTarget";
  73048. this._isDefaultTeleportationTarget = false;
  73049. this._teleportationTarget = value;
  73050. }
  73051. },
  73052. enumerable: true,
  73053. configurable: true
  73054. });
  73055. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  73056. get: function () {
  73057. return this._displayGaze;
  73058. },
  73059. set: function (value) {
  73060. this._displayGaze = value;
  73061. if (!value) {
  73062. this._gazeTracker.isVisible = false;
  73063. }
  73064. },
  73065. enumerable: true,
  73066. configurable: true
  73067. });
  73068. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  73069. get: function () {
  73070. return this._displayLaserPointer;
  73071. },
  73072. set: function (value) {
  73073. this._displayLaserPointer = value;
  73074. if (!value) {
  73075. if (this._rightLaserPointer) {
  73076. this._rightLaserPointer.isVisible = false;
  73077. }
  73078. if (this._leftLaserPointer) {
  73079. this._leftLaserPointer.isVisible = false;
  73080. }
  73081. }
  73082. else {
  73083. if (this._rightLaserPointer) {
  73084. this._rightLaserPointer.isVisible = true;
  73085. }
  73086. else if (this._leftLaserPointer) {
  73087. this._leftLaserPointer.isVisible = true;
  73088. }
  73089. }
  73090. },
  73091. enumerable: true,
  73092. configurable: true
  73093. });
  73094. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  73095. get: function () {
  73096. return this._deviceOrientationCamera;
  73097. },
  73098. enumerable: true,
  73099. configurable: true
  73100. });
  73101. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  73102. // Based on the current WebVR support, returns the current VR camera used
  73103. get: function () {
  73104. if (this._webVRready) {
  73105. return this._webVRCamera;
  73106. }
  73107. else {
  73108. return this._scene.activeCamera;
  73109. }
  73110. },
  73111. enumerable: true,
  73112. configurable: true
  73113. });
  73114. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  73115. get: function () {
  73116. return this._webVRCamera;
  73117. },
  73118. enumerable: true,
  73119. configurable: true
  73120. });
  73121. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  73122. get: function () {
  73123. return this._vrDeviceOrientationCamera;
  73124. },
  73125. enumerable: true,
  73126. configurable: true
  73127. });
  73128. // Raised when one of the controller has loaded successfully its associated default mesh
  73129. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  73130. this._tryEnableInteractionOnController(webVRController);
  73131. try {
  73132. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  73133. }
  73134. catch (err) {
  73135. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  73136. }
  73137. };
  73138. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  73139. /**
  73140. * Gets a value indicating if we are currently in VR mode.
  73141. */
  73142. get: function () {
  73143. return this._webVRpresenting || this._fullscreenVRpresenting;
  73144. },
  73145. enumerable: true,
  73146. configurable: true
  73147. });
  73148. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  73149. var vrDisplay = this._scene.getEngine().getVRDevice();
  73150. if (vrDisplay) {
  73151. var wasPresenting = this._webVRpresenting;
  73152. // A VR display is connected
  73153. this._webVRpresenting = vrDisplay.isPresenting;
  73154. if (wasPresenting && !this._webVRpresenting)
  73155. this.exitVR();
  73156. }
  73157. else {
  73158. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  73159. }
  73160. this.updateButtonVisibility();
  73161. };
  73162. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  73163. this._webVRsupported = eventArgs.vrSupported;
  73164. this._webVRready = !!eventArgs.vrDisplay;
  73165. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  73166. this.updateButtonVisibility();
  73167. };
  73168. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  73169. if (this._canvas && !this._useCustomVRButton) {
  73170. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  73171. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  73172. }
  73173. };
  73174. VRExperienceHelper.prototype.displayVRButton = function () {
  73175. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  73176. document.body.appendChild(this._btnVR);
  73177. this._btnVRDisplayed = true;
  73178. }
  73179. };
  73180. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  73181. if (!this._btnVR || this._useCustomVRButton) {
  73182. return;
  73183. }
  73184. this._btnVR.className = "babylonVRicon";
  73185. if (this.isInVRMode) {
  73186. this._btnVR.className += " vrdisplaypresenting";
  73187. }
  73188. else {
  73189. if (this._webVRready)
  73190. this._btnVR.className += " vrdisplayready";
  73191. if (this._webVRsupported)
  73192. this._btnVR.className += " vrdisplaysupported";
  73193. if (this._webVRrequesting)
  73194. this._btnVR.className += " vrdisplayrequesting";
  73195. }
  73196. };
  73197. /**
  73198. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  73199. * Otherwise, will use the fullscreen API.
  73200. */
  73201. VRExperienceHelper.prototype.enterVR = function () {
  73202. if (this.onEnteringVRObservable) {
  73203. try {
  73204. this.onEnteringVRObservable.notifyObservers(this);
  73205. }
  73206. catch (err) {
  73207. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  73208. }
  73209. }
  73210. if (this._scene.activeCamera) {
  73211. this._position = this._scene.activeCamera.position.clone();
  73212. // make sure that we return to the last active camera
  73213. this._existingCamera = this._scene.activeCamera;
  73214. }
  73215. if (this._webVRrequesting)
  73216. return;
  73217. // If WebVR is supported and a headset is connected
  73218. if (this._webVRready) {
  73219. if (!this._webVRpresenting) {
  73220. this._webVRCamera.position = this._position;
  73221. this._scene.activeCamera = this._webVRCamera;
  73222. }
  73223. }
  73224. else if (this._vrDeviceOrientationCamera) {
  73225. this._vrDeviceOrientationCamera.position = this._position;
  73226. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  73227. this._scene.getEngine().switchFullscreen(true);
  73228. this.updateButtonVisibility();
  73229. }
  73230. if (this._scene.activeCamera && this._canvas) {
  73231. this._scene.activeCamera.attachControl(this._canvas);
  73232. }
  73233. if (this._interactionsEnabled) {
  73234. this._scene.registerBeforeRender(this.beforeRender);
  73235. }
  73236. };
  73237. /**
  73238. * Attempt to exit VR, or fullscreen.
  73239. */
  73240. VRExperienceHelper.prototype.exitVR = function () {
  73241. if (this.onExitingVRObservable) {
  73242. try {
  73243. this.onExitingVRObservable.notifyObservers(this);
  73244. }
  73245. catch (err) {
  73246. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  73247. }
  73248. }
  73249. if (this._webVRpresenting) {
  73250. this._scene.getEngine().disableVR();
  73251. }
  73252. if (this._scene.activeCamera) {
  73253. this._position = this._scene.activeCamera.position.clone();
  73254. }
  73255. if (this._deviceOrientationCamera) {
  73256. this._deviceOrientationCamera.position = this._position;
  73257. this._scene.activeCamera = this._deviceOrientationCamera;
  73258. if (this._canvas) {
  73259. this._scene.activeCamera.attachControl(this._canvas);
  73260. }
  73261. }
  73262. else if (this._existingCamera) {
  73263. this._existingCamera.position = this._position;
  73264. this._scene.activeCamera = this._existingCamera;
  73265. }
  73266. this.updateButtonVisibility();
  73267. if (this._interactionsEnabled) {
  73268. this._scene.unregisterBeforeRender(this.beforeRender);
  73269. }
  73270. };
  73271. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  73272. get: function () {
  73273. return this._position;
  73274. },
  73275. set: function (value) {
  73276. this._position = value;
  73277. if (this._scene.activeCamera) {
  73278. this._scene.activeCamera.position = value;
  73279. }
  73280. },
  73281. enumerable: true,
  73282. configurable: true
  73283. });
  73284. VRExperienceHelper.prototype.enableInteractions = function () {
  73285. var _this = this;
  73286. if (!this._interactionsEnabled) {
  73287. this._interactionsRequested = true;
  73288. if (this._leftControllerReady && this._webVRCamera.leftController) {
  73289. this._enableInteractionOnController(this._webVRCamera.leftController);
  73290. }
  73291. if (this._rightControllerReady && this._webVRCamera.rightController) {
  73292. this._enableInteractionOnController(this._webVRCamera.rightController);
  73293. }
  73294. this._createGazeTracker();
  73295. this.raySelectionPredicate = function (mesh) {
  73296. return true;
  73297. };
  73298. this.meshSelectionPredicate = function (mesh) {
  73299. return true;
  73300. };
  73301. this._raySelectionPredicate = function (mesh) {
  73302. if (_this._isTeleportationFloor(mesh) || (mesh.isVisible && mesh.name.indexOf("gazeTracker") === -1
  73303. && mesh.name.indexOf("teleportationTarget") === -1
  73304. && mesh.name.indexOf("torusTeleportation") === -1
  73305. && mesh.name.indexOf("laserPointer") === -1)) {
  73306. return _this.raySelectionPredicate(mesh);
  73307. }
  73308. return false;
  73309. };
  73310. this._interactionsEnabled = true;
  73311. }
  73312. };
  73313. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  73314. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  73315. if (this._floorMeshesCollection[i].id === mesh.id) {
  73316. return true;
  73317. }
  73318. }
  73319. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  73320. return true;
  73321. }
  73322. return false;
  73323. };
  73324. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  73325. if (!this._floorMeshesCollection) {
  73326. return;
  73327. }
  73328. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  73329. return;
  73330. }
  73331. this._floorMeshesCollection.push(floorMesh);
  73332. };
  73333. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  73334. if (!this._floorMeshesCollection) {
  73335. return;
  73336. }
  73337. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  73338. if (meshIndex !== -1) {
  73339. this._floorMeshesCollection.splice(meshIndex, 1);
  73340. }
  73341. };
  73342. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  73343. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  73344. if (!this._teleportationEnabled) {
  73345. this._teleportationRequested = true;
  73346. this.enableInteractions();
  73347. if (vrTeleportationOptions.floorMeshName) {
  73348. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  73349. }
  73350. if (vrTeleportationOptions.floorMeshes) {
  73351. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  73352. }
  73353. if (this._leftControllerReady && this._webVRCamera.leftController) {
  73354. this._enableTeleportationOnController(this._webVRCamera.leftController);
  73355. }
  73356. if (this._rightControllerReady && this._webVRCamera.rightController) {
  73357. this._enableTeleportationOnController(this._webVRCamera.rightController);
  73358. }
  73359. // Creates an image processing post process for the vignette not relying
  73360. // on the main scene configuration for image processing to reduce setup and spaces
  73361. // (gamma/linear) conflicts.
  73362. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  73363. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  73364. imageProcessingConfiguration.vignetteEnabled = true;
  73365. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  73366. this._webVRCamera.detachPostProcess(this._postProcessMove);
  73367. this._passProcessMove = new BABYLON.PassPostProcess("pass", 1.0, this._webVRCamera);
  73368. this._teleportationEnabled = true;
  73369. if (this._isDefaultTeleportationTarget) {
  73370. this._createTeleportationCircles();
  73371. }
  73372. }
  73373. };
  73374. VRExperienceHelper.prototype._enableInteractionOnController = function (webVRController) {
  73375. var _this = this;
  73376. var controllerMesh = webVRController.mesh;
  73377. if (controllerMesh) {
  73378. var makeNotPick = function (root) {
  73379. root.name += " laserPointer";
  73380. root.getChildMeshes().forEach(function (c) {
  73381. makeNotPick(c);
  73382. });
  73383. };
  73384. makeNotPick(controllerMesh);
  73385. var childMeshes = controllerMesh.getChildMeshes();
  73386. for (var i = 0; i < childMeshes.length; i++) {
  73387. if (childMeshes[i].name && childMeshes[i].name.indexOf("POINTING_POSE") >= 0) {
  73388. controllerMesh = childMeshes[i];
  73389. break;
  73390. }
  73391. }
  73392. var laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, this._scene, false);
  73393. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", this._scene);
  73394. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  73395. laserPointerMaterial.alpha = 0.6;
  73396. laserPointer.material = laserPointerMaterial;
  73397. laserPointer.rotation.x = Math.PI / 2;
  73398. laserPointer.parent = controllerMesh;
  73399. laserPointer.position.z = -0.5;
  73400. laserPointer.isVisible = false;
  73401. if (webVRController.hand === "left") {
  73402. this._leftLaserPointer = laserPointer;
  73403. this._interactionsEnabledOnLeftController = true;
  73404. if (!this._rightLaserPointer) {
  73405. this._leftLaserPointer.isVisible = true;
  73406. }
  73407. }
  73408. else {
  73409. this._rightLaserPointer = laserPointer;
  73410. this._interactionsEnabledOnRightController = true;
  73411. if (!this._leftLaserPointer) {
  73412. this._rightLaserPointer.isVisible = true;
  73413. }
  73414. }
  73415. webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  73416. // Enabling / disabling laserPointer
  73417. if (_this._displayLaserPointer && stateObject.value === 1) {
  73418. laserPointer.isVisible = !laserPointer.isVisible;
  73419. // Laser pointer can only be active on left or right, not both at the same time
  73420. if (webVRController.hand === "left" && _this._rightLaserPointer) {
  73421. _this._rightLaserPointer.isVisible = false;
  73422. }
  73423. else if (_this._leftLaserPointer) {
  73424. _this._leftLaserPointer.isVisible = false;
  73425. }
  73426. }
  73427. });
  73428. webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  73429. if (!_this._pointerDownOnMeshAsked) {
  73430. if (stateObject.value > _this._padSensibilityUp) {
  73431. _this._selectionPointerDown();
  73432. }
  73433. }
  73434. else if (stateObject.value < _this._padSensibilityDown) {
  73435. _this._selectionPointerUp();
  73436. }
  73437. });
  73438. }
  73439. };
  73440. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, webVRController) {
  73441. if (webVRController === void 0) { webVRController = null; }
  73442. if (!this._teleportationRequestInitiated) {
  73443. if (stateObject.y < -this._padSensibilityUp && this._dpadPressed) {
  73444. if (webVRController) {
  73445. // If laser pointer wasn't enabled yet
  73446. if (this._displayLaserPointer && webVRController.hand === "left" && this._leftLaserPointer) {
  73447. this._leftLaserPointer.isVisible = true;
  73448. if (this._rightLaserPointer) {
  73449. this._rightLaserPointer.isVisible = false;
  73450. }
  73451. }
  73452. else if (this._displayLaserPointer && this._rightLaserPointer) {
  73453. this._rightLaserPointer.isVisible = true;
  73454. if (this._leftLaserPointer) {
  73455. this._leftLaserPointer.isVisible = false;
  73456. }
  73457. }
  73458. }
  73459. this._teleportationRequestInitiated = true;
  73460. }
  73461. }
  73462. else {
  73463. // Listening to the proper controller values changes to confirm teleportation
  73464. if (webVRController == null
  73465. || (webVRController.hand === "left" && this._leftLaserPointer && this._leftLaserPointer.isVisible)
  73466. || (webVRController.hand === "right" && this._rightLaserPointer && this._rightLaserPointer.isVisible)) {
  73467. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  73468. if (this._teleportationAllowed) {
  73469. this._teleportationAllowed = false;
  73470. this._teleportCamera();
  73471. }
  73472. this._teleportationRequestInitiated = false;
  73473. }
  73474. }
  73475. }
  73476. };
  73477. VRExperienceHelper.prototype._selectionPointerDown = function () {
  73478. this._pointerDownOnMeshAsked = true;
  73479. if (this._currentMeshSelected && this._currentHit) {
  73480. this._scene.simulatePointerDown(this._currentHit);
  73481. }
  73482. };
  73483. VRExperienceHelper.prototype._selectionPointerUp = function () {
  73484. if (this._currentMeshSelected && this._currentHit) {
  73485. this._scene.simulatePointerUp(this._currentHit);
  73486. }
  73487. this._pointerDownOnMeshAsked = false;
  73488. };
  73489. VRExperienceHelper.prototype._checkRotate = function (stateObject) {
  73490. // Only rotate when user is not currently selecting a teleportation location
  73491. if (this._teleportationRequestInitiated) {
  73492. return;
  73493. }
  73494. if (!this._rotationLeftAsked) {
  73495. if (stateObject.x < -this._padSensibilityUp && this._dpadPressed) {
  73496. this._rotationLeftAsked = true;
  73497. if (this._rotationAllowed) {
  73498. this._rotateCamera(false);
  73499. }
  73500. }
  73501. }
  73502. else {
  73503. if (stateObject.x > -this._padSensibilityDown) {
  73504. this._rotationLeftAsked = false;
  73505. }
  73506. }
  73507. if (!this._rotationRightAsked) {
  73508. if (stateObject.x > this._padSensibilityUp && this._dpadPressed) {
  73509. this._rotationRightAsked = true;
  73510. if (this._rotationAllowed) {
  73511. this._rotateCamera(true);
  73512. }
  73513. }
  73514. }
  73515. else {
  73516. if (stateObject.x < this._padSensibilityDown) {
  73517. this._rotationRightAsked = false;
  73518. }
  73519. }
  73520. };
  73521. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject) {
  73522. // Only teleport backwards when user is not currently selecting a teleportation location
  73523. if (this._teleportationRequestInitiated) {
  73524. return;
  73525. }
  73526. // Teleport backwards
  73527. if (stateObject.y > this._padSensibilityUp && this._dpadPressed) {
  73528. if (!this._teleportationBackRequestInitiated) {
  73529. if (!this.currentVRCamera) {
  73530. return;
  73531. }
  73532. // Get rotation and position of the current camera
  73533. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  73534. var position = this.currentVRCamera.position;
  73535. // If the camera has device position, use that instead
  73536. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  73537. rotation = this.currentVRCamera.deviceRotationQuaternion;
  73538. position = this.currentVRCamera.devicePosition;
  73539. }
  73540. // Get matrix with only the y rotation of the device rotation
  73541. rotation.toEulerAnglesToRef(this._workingVector);
  73542. this._workingVector.z = 0;
  73543. this._workingVector.x = 0;
  73544. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  73545. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  73546. // Rotate backwards ray by device rotation to cast at the ground behind the user
  73547. BABYLON.Vector3.TransformCoordinatesToRef(this.teleportBackwardsVector, this._workingMatrix, this._workingVector);
  73548. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  73549. var ray = new BABYLON.Ray(position, this._workingVector);
  73550. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  73551. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  73552. this._teleportCamera(hit.pickedPoint);
  73553. }
  73554. this._teleportationBackRequestInitiated = true;
  73555. }
  73556. }
  73557. else {
  73558. this._teleportationBackRequestInitiated = false;
  73559. }
  73560. };
  73561. VRExperienceHelper.prototype._enableTeleportationOnController = function (webVRController) {
  73562. var _this = this;
  73563. var controllerMesh = webVRController.mesh;
  73564. if (controllerMesh) {
  73565. if (webVRController.hand === "left") {
  73566. if (!this._interactionsEnabledOnLeftController) {
  73567. this._enableInteractionOnController(webVRController);
  73568. }
  73569. this._teleportationEnabledOnLeftController = true;
  73570. }
  73571. else {
  73572. if (!this._interactionsEnabledOnRightController) {
  73573. this._enableInteractionOnController(webVRController);
  73574. }
  73575. this._teleportationEnabledOnRightController = true;
  73576. }
  73577. if (webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  73578. this._dpadPressed = false;
  73579. webVRController.onPadStateChangedObservable.add(function (stateObject) {
  73580. _this._dpadPressed = stateObject.pressed;
  73581. if (!_this._dpadPressed) {
  73582. _this._rotationLeftAsked = false;
  73583. _this._rotationRightAsked = false;
  73584. _this._teleportationBackRequestInitiated = false;
  73585. }
  73586. });
  73587. }
  73588. webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  73589. _this._checkTeleportBackwards(stateObject);
  73590. _this._checkTeleportWithRay(stateObject, webVRController);
  73591. _this._checkRotate(stateObject);
  73592. });
  73593. }
  73594. };
  73595. // Gaze support used to point to teleport or to interact with an object
  73596. VRExperienceHelper.prototype._createGazeTracker = function () {
  73597. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, this._scene, false);
  73598. this._gazeTracker.bakeCurrentTransformIntoVertices();
  73599. this._gazeTracker.isPickable = false;
  73600. this._gazeTracker.isVisible = false;
  73601. var targetMat = new BABYLON.StandardMaterial("targetMat", this._scene);
  73602. targetMat.specularColor = BABYLON.Color3.Black();
  73603. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  73604. targetMat.backFaceCulling = false;
  73605. this._gazeTracker.material = targetMat;
  73606. };
  73607. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  73608. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  73609. this._teleportationTarget.isPickable = false;
  73610. var length = 512;
  73611. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  73612. dynamicTexture.hasAlpha = true;
  73613. var context = dynamicTexture.getContext();
  73614. var centerX = length / 2;
  73615. var centerY = length / 2;
  73616. var radius = 200;
  73617. context.beginPath();
  73618. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  73619. context.fillStyle = this._teleportationFillColor;
  73620. context.fill();
  73621. context.lineWidth = 10;
  73622. context.strokeStyle = this._teleportationBorderColor;
  73623. context.stroke();
  73624. context.closePath();
  73625. dynamicTexture.update();
  73626. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  73627. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  73628. this._teleportationTarget.material = teleportationCircleMaterial;
  73629. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  73630. torus.isPickable = false;
  73631. torus.parent = this._teleportationTarget;
  73632. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  73633. var keys = [];
  73634. keys.push({
  73635. frame: 0,
  73636. value: 0
  73637. });
  73638. keys.push({
  73639. frame: 30,
  73640. value: 0.4
  73641. });
  73642. keys.push({
  73643. frame: 60,
  73644. value: 0
  73645. });
  73646. animationInnerCircle.setKeys(keys);
  73647. var easingFunction = new BABYLON.SineEase();
  73648. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  73649. animationInnerCircle.setEasingFunction(easingFunction);
  73650. torus.animations = [];
  73651. torus.animations.push(animationInnerCircle);
  73652. this._scene.beginAnimation(torus, 0, 60, true);
  73653. this._hideTeleportationTarget();
  73654. };
  73655. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  73656. if (this._teleportationEnabled) {
  73657. this._teleportationTarget.isVisible = true;
  73658. if (this._isDefaultTeleportationTarget) {
  73659. this._teleportationTarget.getChildren()[0].isVisible = true;
  73660. }
  73661. }
  73662. };
  73663. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  73664. if (this._teleportationEnabled) {
  73665. this._teleportationTarget.isVisible = false;
  73666. if (this._isDefaultTeleportationTarget) {
  73667. this._teleportationTarget.getChildren()[0].isVisible = false;
  73668. }
  73669. }
  73670. };
  73671. VRExperienceHelper.prototype._rotateCamera = function (right) {
  73672. var _this = this;
  73673. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  73674. return;
  73675. }
  73676. if (right) {
  73677. this._rotationAngle++;
  73678. }
  73679. else {
  73680. this._rotationAngle--;
  73681. }
  73682. this.currentVRCamera.animations = [];
  73683. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  73684. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  73685. var animationRotationKeys = [];
  73686. animationRotationKeys.push({
  73687. frame: 0,
  73688. value: this.currentVRCamera.rotationQuaternion
  73689. });
  73690. animationRotationKeys.push({
  73691. frame: 6,
  73692. value: target
  73693. });
  73694. animationRotation.setKeys(animationRotationKeys);
  73695. animationRotation.setEasingFunction(this._circleEase);
  73696. this.currentVRCamera.animations.push(animationRotation);
  73697. this._postProcessMove.animations = [];
  73698. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  73699. var vignetteWeightKeys = [];
  73700. vignetteWeightKeys.push({
  73701. frame: 0,
  73702. value: 0
  73703. });
  73704. vignetteWeightKeys.push({
  73705. frame: 3,
  73706. value: 4
  73707. });
  73708. vignetteWeightKeys.push({
  73709. frame: 6,
  73710. value: 0
  73711. });
  73712. animationPP.setKeys(vignetteWeightKeys);
  73713. animationPP.setEasingFunction(this._circleEase);
  73714. this._postProcessMove.animations.push(animationPP);
  73715. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  73716. var vignetteStretchKeys = [];
  73717. vignetteStretchKeys.push({
  73718. frame: 0,
  73719. value: 0
  73720. });
  73721. vignetteStretchKeys.push({
  73722. frame: 3,
  73723. value: 10
  73724. });
  73725. vignetteStretchKeys.push({
  73726. frame: 6,
  73727. value: 0
  73728. });
  73729. animationPP2.setKeys(vignetteStretchKeys);
  73730. animationPP2.setEasingFunction(this._circleEase);
  73731. this._postProcessMove.animations.push(animationPP2);
  73732. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  73733. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  73734. this._webVRCamera.attachPostProcess(this._postProcessMove);
  73735. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  73736. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  73737. });
  73738. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  73739. };
  73740. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit) {
  73741. if (hit.pickedPoint) {
  73742. this._teleportationAllowed = true;
  73743. if (this._teleportationRequestInitiated) {
  73744. this._displayTeleportationTarget();
  73745. }
  73746. else {
  73747. this._hideTeleportationTarget();
  73748. }
  73749. this._haloCenter.copyFrom(hit.pickedPoint);
  73750. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  73751. var pickNormal = hit.getNormal(true, false);
  73752. if (pickNormal) {
  73753. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  73754. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  73755. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  73756. }
  73757. this._teleportationTarget.position.y += 0.1;
  73758. }
  73759. };
  73760. VRExperienceHelper.prototype._teleportCamera = function (location) {
  73761. var _this = this;
  73762. if (location === void 0) { location = null; }
  73763. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  73764. return;
  73765. }
  73766. if (!location) {
  73767. location = this._haloCenter;
  73768. }
  73769. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  73770. // offset of the headset from the anchor.
  73771. if (this.webVRCamera.leftCamera) {
  73772. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  73773. this._workingVector.subtractInPlace(this.webVRCamera.position);
  73774. location.subtractToRef(this._workingVector, this._workingVector);
  73775. }
  73776. else {
  73777. this._workingVector.copyFrom(location);
  73778. }
  73779. // Add height to account for user's height offset
  73780. if (this.isInVRMode) {
  73781. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround();
  73782. }
  73783. else {
  73784. this._workingVector.y += this._defaultHeight;
  73785. }
  73786. // Create animation from the camera's position to the new location
  73787. this.currentVRCamera.animations = [];
  73788. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  73789. var animationCameraTeleportationKeys = [{
  73790. frame: 0,
  73791. value: this.currentVRCamera.position
  73792. },
  73793. {
  73794. frame: 11,
  73795. value: this._workingVector
  73796. }
  73797. ];
  73798. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  73799. animationCameraTeleportation.setEasingFunction(this._circleEase);
  73800. this.currentVRCamera.animations.push(animationCameraTeleportation);
  73801. this._postProcessMove.animations = [];
  73802. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  73803. var vignetteWeightKeys = [];
  73804. vignetteWeightKeys.push({
  73805. frame: 0,
  73806. value: 0
  73807. });
  73808. vignetteWeightKeys.push({
  73809. frame: 5,
  73810. value: 8
  73811. });
  73812. vignetteWeightKeys.push({
  73813. frame: 11,
  73814. value: 0
  73815. });
  73816. animationPP.setKeys(vignetteWeightKeys);
  73817. this._postProcessMove.animations.push(animationPP);
  73818. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  73819. var vignetteStretchKeys = [];
  73820. vignetteStretchKeys.push({
  73821. frame: 0,
  73822. value: 0
  73823. });
  73824. vignetteStretchKeys.push({
  73825. frame: 5,
  73826. value: 10
  73827. });
  73828. vignetteStretchKeys.push({
  73829. frame: 11,
  73830. value: 0
  73831. });
  73832. animationPP2.setKeys(vignetteStretchKeys);
  73833. this._postProcessMove.animations.push(animationPP2);
  73834. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  73835. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  73836. this._webVRCamera.attachPostProcess(this._postProcessMove);
  73837. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  73838. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  73839. });
  73840. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1);
  73841. };
  73842. VRExperienceHelper.prototype._castRayAndSelectObject = function () {
  73843. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  73844. return;
  73845. }
  73846. var ray;
  73847. if (this._leftLaserPointer && this._leftLaserPointer.isVisible && this.currentVRCamera.leftController) {
  73848. ray = this.currentVRCamera.leftController.getForwardRay(this._rayLength);
  73849. }
  73850. else if (this._rightLaserPointer && this._rightLaserPointer.isVisible && this.currentVRCamera.rightController) {
  73851. ray = this.currentVRCamera.rightController.getForwardRay(this._rayLength);
  73852. }
  73853. else {
  73854. ray = this.currentVRCamera.getForwardRay(this._rayLength);
  73855. }
  73856. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  73857. // Moving the gazeTracker on the mesh face targetted
  73858. if (hit && hit.pickedPoint) {
  73859. if (this._displayGaze) {
  73860. var multiplier = 1;
  73861. this._gazeTracker.isVisible = true;
  73862. if (this._isActionableMesh) {
  73863. multiplier = 3;
  73864. }
  73865. this._gazeTracker.scaling.x = hit.distance * multiplier;
  73866. this._gazeTracker.scaling.y = hit.distance * multiplier;
  73867. this._gazeTracker.scaling.z = hit.distance * multiplier;
  73868. var pickNormal = hit.getNormal();
  73869. // To avoid z-fighting
  73870. var deltaFighting = 0.002;
  73871. if (pickNormal) {
  73872. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  73873. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  73874. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._gazeTracker.rotation);
  73875. }
  73876. this._gazeTracker.position.copyFrom(hit.pickedPoint);
  73877. if (this._gazeTracker.position.x < 0) {
  73878. this._gazeTracker.position.x += deltaFighting;
  73879. }
  73880. else {
  73881. this._gazeTracker.position.x -= deltaFighting;
  73882. }
  73883. if (this._gazeTracker.position.y < 0) {
  73884. this._gazeTracker.position.y += deltaFighting;
  73885. }
  73886. else {
  73887. this._gazeTracker.position.y -= deltaFighting;
  73888. }
  73889. if (this._gazeTracker.position.z < 0) {
  73890. this._gazeTracker.position.z += deltaFighting;
  73891. }
  73892. else {
  73893. this._gazeTracker.position.z -= deltaFighting;
  73894. }
  73895. }
  73896. // Changing the size of the laser pointer based on the distance from the targetted point
  73897. if (this._rightLaserPointer && this._rightLaserPointer.isVisible) {
  73898. this._rightLaserPointer.scaling.y = hit.distance;
  73899. this._rightLaserPointer.position.z = -hit.distance / 2;
  73900. }
  73901. if (this._leftLaserPointer && this._leftLaserPointer.isVisible) {
  73902. this._leftLaserPointer.scaling.y = hit.distance;
  73903. this._leftLaserPointer.position.z = -hit.distance / 2;
  73904. }
  73905. }
  73906. else {
  73907. this._gazeTracker.isVisible = false;
  73908. }
  73909. if (hit && hit.pickedMesh) {
  73910. this._currentHit = hit;
  73911. if (this._pointerDownOnMeshAsked) {
  73912. this._scene.simulatePointerMove(this._currentHit);
  73913. }
  73914. // The object selected is the floor, we're in a teleportation scenario
  73915. if (this._teleportationEnabled && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  73916. // Moving the teleportation area to this targetted point
  73917. this._moveTeleportationSelectorTo(hit);
  73918. return;
  73919. }
  73920. // If not, we're in a selection scenario
  73921. this._hideTeleportationTarget();
  73922. this._teleportationAllowed = false;
  73923. if (hit.pickedMesh !== this._currentMeshSelected) {
  73924. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  73925. this._currentMeshSelected = hit.pickedMesh;
  73926. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  73927. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  73928. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  73929. this._isActionableMesh = true;
  73930. }
  73931. else {
  73932. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  73933. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  73934. this._isActionableMesh = false;
  73935. }
  73936. try {
  73937. this.onNewMeshSelected.notifyObservers(this._currentMeshSelected);
  73938. }
  73939. catch (err) {
  73940. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  73941. }
  73942. }
  73943. else {
  73944. if (this._currentMeshSelected) {
  73945. this.onSelectedMeshUnselected.notifyObservers(this._currentMeshSelected);
  73946. }
  73947. this._currentMeshSelected = null;
  73948. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  73949. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  73950. }
  73951. }
  73952. }
  73953. else {
  73954. this._currentHit = null;
  73955. this._currentMeshSelected = null;
  73956. this._teleportationAllowed = false;
  73957. this._hideTeleportationTarget();
  73958. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  73959. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  73960. }
  73961. };
  73962. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  73963. if (this._leftLaserPointer && this._leftLaserPointer.material) {
  73964. this._leftLaserPointer.material.emissiveColor = color;
  73965. }
  73966. if (this._rightLaserPointer && this._rightLaserPointer.material) {
  73967. this._rightLaserPointer.material.emissiveColor = color;
  73968. }
  73969. };
  73970. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  73971. if (this._gazeTracker.material) {
  73972. this._gazeTracker.material.emissiveColor = color;
  73973. }
  73974. };
  73975. VRExperienceHelper.prototype.dispose = function () {
  73976. if (this.isInVRMode) {
  73977. this.exitVR();
  73978. }
  73979. if (this._passProcessMove) {
  73980. this._passProcessMove.dispose();
  73981. }
  73982. if (this._postProcessMove) {
  73983. this._postProcessMove.dispose();
  73984. }
  73985. if (this._webVRCamera) {
  73986. this._webVRCamera.dispose();
  73987. }
  73988. if (this._vrDeviceOrientationCamera) {
  73989. this._vrDeviceOrientationCamera.dispose();
  73990. }
  73991. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  73992. document.body.removeChild(this._btnVR);
  73993. }
  73994. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  73995. this._deviceOrientationCamera.dispose();
  73996. }
  73997. if (this._gazeTracker) {
  73998. this._gazeTracker.dispose();
  73999. }
  74000. if (this._teleportationTarget) {
  74001. this._teleportationTarget.dispose();
  74002. }
  74003. this._floorMeshesCollection = [];
  74004. document.removeEventListener("keydown", this._onKeyDown);
  74005. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  74006. window.removeEventListener("resize", this._onResize);
  74007. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  74008. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  74009. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  74010. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  74011. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  74012. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  74013. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  74014. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  74015. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  74016. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  74017. this._scene.unregisterBeforeRender(this.beforeRender);
  74018. };
  74019. VRExperienceHelper.prototype.getClassName = function () {
  74020. return "VRExperienceHelper";
  74021. };
  74022. return VRExperienceHelper;
  74023. }());
  74024. BABYLON.VRExperienceHelper = VRExperienceHelper;
  74025. })(BABYLON || (BABYLON = {}));
  74026. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  74027. // Mainly based on these 2 articles :
  74028. // 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
  74029. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  74030. var BABYLON;
  74031. (function (BABYLON) {
  74032. var JoystickAxis;
  74033. (function (JoystickAxis) {
  74034. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  74035. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  74036. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  74037. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  74038. var VirtualJoystick = /** @class */ (function () {
  74039. function VirtualJoystick(leftJoystick) {
  74040. var _this = this;
  74041. if (leftJoystick) {
  74042. this._leftJoystick = true;
  74043. }
  74044. else {
  74045. this._leftJoystick = false;
  74046. }
  74047. VirtualJoystick._globalJoystickIndex++;
  74048. // By default left & right arrow keys are moving the X
  74049. // and up & down keys are moving the Y
  74050. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  74051. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  74052. this.reverseLeftRight = false;
  74053. this.reverseUpDown = false;
  74054. // collections of pointers
  74055. this._touches = new BABYLON.StringDictionary();
  74056. this.deltaPosition = BABYLON.Vector3.Zero();
  74057. this._joystickSensibility = 25;
  74058. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  74059. this._onResize = function (evt) {
  74060. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  74061. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  74062. if (VirtualJoystick.vjCanvas) {
  74063. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  74064. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  74065. }
  74066. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  74067. };
  74068. // injecting a canvas element on top of the canvas 3D game
  74069. if (!VirtualJoystick.vjCanvas) {
  74070. window.addEventListener("resize", this._onResize, false);
  74071. VirtualJoystick.vjCanvas = document.createElement("canvas");
  74072. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  74073. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  74074. VirtualJoystick.vjCanvas.width = window.innerWidth;
  74075. VirtualJoystick.vjCanvas.height = window.innerHeight;
  74076. VirtualJoystick.vjCanvas.style.width = "100%";
  74077. VirtualJoystick.vjCanvas.style.height = "100%";
  74078. VirtualJoystick.vjCanvas.style.position = "absolute";
  74079. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  74080. VirtualJoystick.vjCanvas.style.top = "0px";
  74081. VirtualJoystick.vjCanvas.style.left = "0px";
  74082. VirtualJoystick.vjCanvas.style.zIndex = "5";
  74083. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  74084. // Support for jQuery PEP polyfill
  74085. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  74086. var context = VirtualJoystick.vjCanvas.getContext('2d');
  74087. if (!context) {
  74088. throw new Error("Unable to create canvas for virtual joystick");
  74089. }
  74090. VirtualJoystick.vjCanvasContext = context;
  74091. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  74092. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  74093. document.body.appendChild(VirtualJoystick.vjCanvas);
  74094. }
  74095. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  74096. this.pressed = false;
  74097. // default joystick color
  74098. this._joystickColor = "cyan";
  74099. this._joystickPointerID = -1;
  74100. // current joystick position
  74101. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  74102. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  74103. // origin joystick position
  74104. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  74105. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  74106. this._onPointerDownHandlerRef = function (evt) {
  74107. _this._onPointerDown(evt);
  74108. };
  74109. this._onPointerMoveHandlerRef = function (evt) {
  74110. _this._onPointerMove(evt);
  74111. };
  74112. this._onPointerUpHandlerRef = function (evt) {
  74113. _this._onPointerUp(evt);
  74114. };
  74115. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  74116. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  74117. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  74118. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  74119. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  74120. evt.preventDefault(); // Disables system menu
  74121. }, false);
  74122. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  74123. }
  74124. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  74125. this._joystickSensibility = newJoystickSensibility;
  74126. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  74127. };
  74128. VirtualJoystick.prototype._onPointerDown = function (e) {
  74129. var positionOnScreenCondition;
  74130. e.preventDefault();
  74131. if (this._leftJoystick === true) {
  74132. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  74133. }
  74134. else {
  74135. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  74136. }
  74137. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  74138. // First contact will be dedicated to the virtual joystick
  74139. this._joystickPointerID = e.pointerId;
  74140. this._joystickPointerStartPos.x = e.clientX;
  74141. this._joystickPointerStartPos.y = e.clientY;
  74142. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  74143. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  74144. this._deltaJoystickVector.x = 0;
  74145. this._deltaJoystickVector.y = 0;
  74146. this.pressed = true;
  74147. this._touches.add(e.pointerId.toString(), e);
  74148. }
  74149. else {
  74150. // You can only trigger the action buttons with a joystick declared
  74151. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  74152. this._action();
  74153. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  74154. }
  74155. }
  74156. };
  74157. VirtualJoystick.prototype._onPointerMove = function (e) {
  74158. // If the current pointer is the one associated to the joystick (first touch contact)
  74159. if (this._joystickPointerID == e.pointerId) {
  74160. this._joystickPointerPos.x = e.clientX;
  74161. this._joystickPointerPos.y = e.clientY;
  74162. this._deltaJoystickVector = this._joystickPointerPos.clone();
  74163. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  74164. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  74165. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  74166. switch (this._axisTargetedByLeftAndRight) {
  74167. case JoystickAxis.X:
  74168. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  74169. break;
  74170. case JoystickAxis.Y:
  74171. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  74172. break;
  74173. case JoystickAxis.Z:
  74174. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  74175. break;
  74176. }
  74177. var directionUpDown = this.reverseUpDown ? 1 : -1;
  74178. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  74179. switch (this._axisTargetedByUpAndDown) {
  74180. case JoystickAxis.X:
  74181. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  74182. break;
  74183. case JoystickAxis.Y:
  74184. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  74185. break;
  74186. case JoystickAxis.Z:
  74187. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  74188. break;
  74189. }
  74190. }
  74191. else {
  74192. var data = this._touches.get(e.pointerId.toString());
  74193. if (data) {
  74194. data.x = e.clientX;
  74195. data.y = e.clientY;
  74196. }
  74197. }
  74198. };
  74199. VirtualJoystick.prototype._onPointerUp = function (e) {
  74200. if (this._joystickPointerID == e.pointerId) {
  74201. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  74202. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  74203. this._joystickPointerID = -1;
  74204. this.pressed = false;
  74205. }
  74206. else {
  74207. var touch = this._touches.get(e.pointerId.toString());
  74208. if (touch) {
  74209. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  74210. }
  74211. }
  74212. this._deltaJoystickVector.x = 0;
  74213. this._deltaJoystickVector.y = 0;
  74214. this._touches.remove(e.pointerId.toString());
  74215. };
  74216. /**
  74217. * Change the color of the virtual joystick
  74218. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  74219. */
  74220. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  74221. this._joystickColor = newColor;
  74222. };
  74223. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  74224. this._action = action;
  74225. };
  74226. // Define which axis you'd like to control for left & right
  74227. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  74228. switch (axis) {
  74229. case JoystickAxis.X:
  74230. case JoystickAxis.Y:
  74231. case JoystickAxis.Z:
  74232. this._axisTargetedByLeftAndRight = axis;
  74233. break;
  74234. default:
  74235. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  74236. break;
  74237. }
  74238. };
  74239. // Define which axis you'd like to control for up & down
  74240. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  74241. switch (axis) {
  74242. case JoystickAxis.X:
  74243. case JoystickAxis.Y:
  74244. case JoystickAxis.Z:
  74245. this._axisTargetedByUpAndDown = axis;
  74246. break;
  74247. default:
  74248. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  74249. break;
  74250. }
  74251. };
  74252. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  74253. var _this = this;
  74254. if (this.pressed) {
  74255. this._touches.forEach(function (key, touch) {
  74256. if (touch.pointerId === _this._joystickPointerID) {
  74257. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  74258. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  74259. VirtualJoystick.vjCanvasContext.beginPath();
  74260. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  74261. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  74262. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  74263. VirtualJoystick.vjCanvasContext.stroke();
  74264. VirtualJoystick.vjCanvasContext.closePath();
  74265. VirtualJoystick.vjCanvasContext.beginPath();
  74266. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  74267. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  74268. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  74269. VirtualJoystick.vjCanvasContext.stroke();
  74270. VirtualJoystick.vjCanvasContext.closePath();
  74271. VirtualJoystick.vjCanvasContext.beginPath();
  74272. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  74273. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  74274. VirtualJoystick.vjCanvasContext.stroke();
  74275. VirtualJoystick.vjCanvasContext.closePath();
  74276. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  74277. }
  74278. else {
  74279. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  74280. VirtualJoystick.vjCanvasContext.beginPath();
  74281. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  74282. VirtualJoystick.vjCanvasContext.beginPath();
  74283. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  74284. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  74285. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  74286. VirtualJoystick.vjCanvasContext.stroke();
  74287. VirtualJoystick.vjCanvasContext.closePath();
  74288. touch.prevX = touch.x;
  74289. touch.prevY = touch.y;
  74290. }
  74291. ;
  74292. });
  74293. }
  74294. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  74295. };
  74296. VirtualJoystick.prototype.releaseCanvas = function () {
  74297. if (VirtualJoystick.vjCanvas) {
  74298. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  74299. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  74300. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  74301. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  74302. window.removeEventListener("resize", this._onResize);
  74303. document.body.removeChild(VirtualJoystick.vjCanvas);
  74304. VirtualJoystick.vjCanvas = null;
  74305. }
  74306. };
  74307. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  74308. VirtualJoystick._globalJoystickIndex = 0;
  74309. return VirtualJoystick;
  74310. }());
  74311. BABYLON.VirtualJoystick = VirtualJoystick;
  74312. })(BABYLON || (BABYLON = {}));
  74313. //# sourceMappingURL=babylon.virtualJoystick.js.map
  74314. var BABYLON;
  74315. (function (BABYLON) {
  74316. // We're mainly based on the logic defined into the FreeCamera code
  74317. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  74318. __extends(VirtualJoysticksCamera, _super);
  74319. function VirtualJoysticksCamera(name, position, scene) {
  74320. var _this = _super.call(this, name, position, scene) || this;
  74321. _this.inputs.addVirtualJoystick();
  74322. return _this;
  74323. }
  74324. VirtualJoysticksCamera.prototype.getClassName = function () {
  74325. return "VirtualJoysticksCamera";
  74326. };
  74327. return VirtualJoysticksCamera;
  74328. }(BABYLON.FreeCamera));
  74329. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  74330. })(BABYLON || (BABYLON = {}));
  74331. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  74332. var BABYLON;
  74333. (function (BABYLON) {
  74334. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  74335. function FreeCameraVirtualJoystickInput() {
  74336. }
  74337. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  74338. return this._leftjoystick;
  74339. };
  74340. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  74341. return this._rightjoystick;
  74342. };
  74343. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  74344. if (this._leftjoystick) {
  74345. var camera = this.camera;
  74346. var speed = camera._computeLocalCameraSpeed() * 50;
  74347. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  74348. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  74349. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  74350. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  74351. if (!this._leftjoystick.pressed) {
  74352. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  74353. }
  74354. if (!this._rightjoystick.pressed) {
  74355. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  74356. }
  74357. }
  74358. };
  74359. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  74360. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  74361. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  74362. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  74363. this._leftjoystick.setJoystickSensibility(0.15);
  74364. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  74365. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  74366. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  74367. this._rightjoystick.reverseUpDown = true;
  74368. this._rightjoystick.setJoystickSensibility(0.05);
  74369. this._rightjoystick.setJoystickColor("yellow");
  74370. };
  74371. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  74372. this._leftjoystick.releaseCanvas();
  74373. this._rightjoystick.releaseCanvas();
  74374. };
  74375. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  74376. return "FreeCameraVirtualJoystickInput";
  74377. };
  74378. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  74379. return "virtualJoystick";
  74380. };
  74381. return FreeCameraVirtualJoystickInput;
  74382. }());
  74383. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  74384. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  74385. })(BABYLON || (BABYLON = {}));
  74386. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  74387. var BABYLON;
  74388. (function (BABYLON) {
  74389. var SimplificationSettings = /** @class */ (function () {
  74390. function SimplificationSettings(quality, distance, optimizeMesh) {
  74391. this.quality = quality;
  74392. this.distance = distance;
  74393. this.optimizeMesh = optimizeMesh;
  74394. }
  74395. return SimplificationSettings;
  74396. }());
  74397. BABYLON.SimplificationSettings = SimplificationSettings;
  74398. var SimplificationQueue = /** @class */ (function () {
  74399. function SimplificationQueue() {
  74400. this.running = false;
  74401. this._simplificationArray = [];
  74402. }
  74403. SimplificationQueue.prototype.addTask = function (task) {
  74404. this._simplificationArray.push(task);
  74405. };
  74406. SimplificationQueue.prototype.executeNext = function () {
  74407. var task = this._simplificationArray.pop();
  74408. if (task) {
  74409. this.running = true;
  74410. this.runSimplification(task);
  74411. }
  74412. else {
  74413. this.running = false;
  74414. }
  74415. };
  74416. SimplificationQueue.prototype.runSimplification = function (task) {
  74417. var _this = this;
  74418. if (task.parallelProcessing) {
  74419. //parallel simplifier
  74420. task.settings.forEach(function (setting) {
  74421. var simplifier = _this.getSimplifier(task);
  74422. simplifier.simplify(setting, function (newMesh) {
  74423. task.mesh.addLODLevel(setting.distance, newMesh);
  74424. newMesh.isVisible = true;
  74425. //check if it is the last
  74426. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  74427. //all done, run the success callback.
  74428. task.successCallback();
  74429. }
  74430. _this.executeNext();
  74431. });
  74432. });
  74433. }
  74434. else {
  74435. //single simplifier.
  74436. var simplifier = this.getSimplifier(task);
  74437. var runDecimation = function (setting, callback) {
  74438. simplifier.simplify(setting, function (newMesh) {
  74439. task.mesh.addLODLevel(setting.distance, newMesh);
  74440. newMesh.isVisible = true;
  74441. //run the next quality level
  74442. callback();
  74443. });
  74444. };
  74445. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  74446. runDecimation(task.settings[loop.index], function () {
  74447. loop.executeNext();
  74448. });
  74449. }, function () {
  74450. //execution ended, run the success callback.
  74451. if (task.successCallback) {
  74452. task.successCallback();
  74453. }
  74454. _this.executeNext();
  74455. });
  74456. }
  74457. };
  74458. SimplificationQueue.prototype.getSimplifier = function (task) {
  74459. switch (task.simplificationType) {
  74460. case SimplificationType.QUADRATIC:
  74461. default:
  74462. return new QuadraticErrorSimplification(task.mesh);
  74463. }
  74464. };
  74465. return SimplificationQueue;
  74466. }());
  74467. BABYLON.SimplificationQueue = SimplificationQueue;
  74468. /**
  74469. * The implemented types of simplification.
  74470. * At the moment only Quadratic Error Decimation is implemented.
  74471. */
  74472. var SimplificationType;
  74473. (function (SimplificationType) {
  74474. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  74475. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  74476. var DecimationTriangle = /** @class */ (function () {
  74477. function DecimationTriangle(vertices) {
  74478. this.vertices = vertices;
  74479. this.error = new Array(4);
  74480. this.deleted = false;
  74481. this.isDirty = false;
  74482. this.deletePending = false;
  74483. this.borderFactor = 0;
  74484. }
  74485. return DecimationTriangle;
  74486. }());
  74487. BABYLON.DecimationTriangle = DecimationTriangle;
  74488. var DecimationVertex = /** @class */ (function () {
  74489. function DecimationVertex(position, id) {
  74490. this.position = position;
  74491. this.id = id;
  74492. this.isBorder = true;
  74493. this.q = new QuadraticMatrix();
  74494. this.triangleCount = 0;
  74495. this.triangleStart = 0;
  74496. this.originalOffsets = [];
  74497. }
  74498. DecimationVertex.prototype.updatePosition = function (newPosition) {
  74499. this.position.copyFrom(newPosition);
  74500. };
  74501. return DecimationVertex;
  74502. }());
  74503. BABYLON.DecimationVertex = DecimationVertex;
  74504. var QuadraticMatrix = /** @class */ (function () {
  74505. function QuadraticMatrix(data) {
  74506. this.data = new Array(10);
  74507. for (var i = 0; i < 10; ++i) {
  74508. if (data && data[i]) {
  74509. this.data[i] = data[i];
  74510. }
  74511. else {
  74512. this.data[i] = 0;
  74513. }
  74514. }
  74515. }
  74516. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  74517. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  74518. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  74519. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  74520. return det;
  74521. };
  74522. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  74523. for (var i = 0; i < 10; ++i) {
  74524. this.data[i] += matrix.data[i];
  74525. }
  74526. };
  74527. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  74528. for (var i = 0; i < 10; ++i) {
  74529. this.data[i] += data[i];
  74530. }
  74531. };
  74532. QuadraticMatrix.prototype.add = function (matrix) {
  74533. var m = new QuadraticMatrix();
  74534. for (var i = 0; i < 10; ++i) {
  74535. m.data[i] = this.data[i] + matrix.data[i];
  74536. }
  74537. return m;
  74538. };
  74539. QuadraticMatrix.FromData = function (a, b, c, d) {
  74540. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  74541. };
  74542. //returning an array to avoid garbage collection
  74543. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  74544. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  74545. };
  74546. return QuadraticMatrix;
  74547. }());
  74548. BABYLON.QuadraticMatrix = QuadraticMatrix;
  74549. var Reference = /** @class */ (function () {
  74550. function Reference(vertexId, triangleId) {
  74551. this.vertexId = vertexId;
  74552. this.triangleId = triangleId;
  74553. }
  74554. return Reference;
  74555. }());
  74556. BABYLON.Reference = Reference;
  74557. /**
  74558. * An implementation of the Quadratic Error simplification algorithm.
  74559. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  74560. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  74561. * @author RaananW
  74562. */
  74563. var QuadraticErrorSimplification = /** @class */ (function () {
  74564. function QuadraticErrorSimplification(_mesh) {
  74565. this._mesh = _mesh;
  74566. this.syncIterations = 5000;
  74567. this.aggressiveness = 7;
  74568. this.decimationIterations = 100;
  74569. this.boundingBoxEpsilon = BABYLON.Epsilon;
  74570. }
  74571. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  74572. var _this = this;
  74573. this.initDecimatedMesh();
  74574. //iterating through the submeshes array, one after the other.
  74575. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  74576. _this.initWithMesh(loop.index, function () {
  74577. _this.runDecimation(settings, loop.index, function () {
  74578. loop.executeNext();
  74579. });
  74580. }, settings.optimizeMesh);
  74581. }, function () {
  74582. setTimeout(function () {
  74583. successCallback(_this._reconstructedMesh);
  74584. }, 0);
  74585. });
  74586. };
  74587. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  74588. var _this = this;
  74589. var targetCount = ~~(this.triangles.length * settings.quality);
  74590. var deletedTriangles = 0;
  74591. var triangleCount = this.triangles.length;
  74592. var iterationFunction = function (iteration, callback) {
  74593. setTimeout(function () {
  74594. if (iteration % 5 === 0) {
  74595. _this.updateMesh(iteration === 0);
  74596. }
  74597. for (var i = 0; i < _this.triangles.length; ++i) {
  74598. _this.triangles[i].isDirty = false;
  74599. }
  74600. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  74601. var trianglesIterator = function (i) {
  74602. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  74603. var t = _this.triangles[tIdx];
  74604. if (!t)
  74605. return;
  74606. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  74607. return;
  74608. }
  74609. for (var j = 0; j < 3; ++j) {
  74610. if (t.error[j] < threshold) {
  74611. var deleted0 = [];
  74612. var deleted1 = [];
  74613. var v0 = t.vertices[j];
  74614. var v1 = t.vertices[(j + 1) % 3];
  74615. if (v0.isBorder || v1.isBorder)
  74616. continue;
  74617. var p = BABYLON.Vector3.Zero();
  74618. var n = BABYLON.Vector3.Zero();
  74619. var uv = BABYLON.Vector2.Zero();
  74620. var color = new BABYLON.Color4(0, 0, 0, 1);
  74621. _this.calculateError(v0, v1, p, n, uv, color);
  74622. var delTr = new Array();
  74623. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  74624. continue;
  74625. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  74626. continue;
  74627. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  74628. continue;
  74629. var uniqueArray = new Array();
  74630. delTr.forEach(function (deletedT) {
  74631. if (uniqueArray.indexOf(deletedT) === -1) {
  74632. deletedT.deletePending = true;
  74633. uniqueArray.push(deletedT);
  74634. }
  74635. });
  74636. if (uniqueArray.length % 2 !== 0) {
  74637. continue;
  74638. }
  74639. v0.q = v1.q.add(v0.q);
  74640. v0.updatePosition(p);
  74641. var tStart = _this.references.length;
  74642. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  74643. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  74644. var tCount = _this.references.length - tStart;
  74645. if (tCount <= v0.triangleCount) {
  74646. if (tCount) {
  74647. for (var c = 0; c < tCount; c++) {
  74648. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  74649. }
  74650. }
  74651. }
  74652. else {
  74653. v0.triangleStart = tStart;
  74654. }
  74655. v0.triangleCount = tCount;
  74656. break;
  74657. }
  74658. }
  74659. };
  74660. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  74661. }, 0);
  74662. };
  74663. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  74664. if (triangleCount - deletedTriangles <= targetCount)
  74665. loop.breakLoop();
  74666. else {
  74667. iterationFunction(loop.index, function () {
  74668. loop.executeNext();
  74669. });
  74670. }
  74671. }, function () {
  74672. setTimeout(function () {
  74673. //reconstruct this part of the mesh
  74674. _this.reconstructMesh(submeshIndex);
  74675. successCallback();
  74676. }, 0);
  74677. });
  74678. };
  74679. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  74680. var _this = this;
  74681. this.vertices = [];
  74682. this.triangles = [];
  74683. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  74684. var indices = this._mesh.getIndices();
  74685. var submesh = this._mesh.subMeshes[submeshIndex];
  74686. var findInVertices = function (positionToSearch) {
  74687. if (optimizeMesh) {
  74688. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  74689. if (_this.vertices[ii].position.equals(positionToSearch)) {
  74690. return _this.vertices[ii];
  74691. }
  74692. }
  74693. }
  74694. return null;
  74695. };
  74696. var vertexReferences = [];
  74697. var vertexInit = function (i) {
  74698. if (!positionData) {
  74699. return;
  74700. }
  74701. var offset = i + submesh.verticesStart;
  74702. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  74703. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  74704. vertex.originalOffsets.push(offset);
  74705. if (vertex.id === _this.vertices.length) {
  74706. _this.vertices.push(vertex);
  74707. }
  74708. vertexReferences.push(vertex.id);
  74709. };
  74710. //var totalVertices = mesh.getTotalVertices();
  74711. var totalVertices = submesh.verticesCount;
  74712. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  74713. var indicesInit = function (i) {
  74714. if (!indices) {
  74715. return;
  74716. }
  74717. var offset = (submesh.indexStart / 3) + i;
  74718. var pos = (offset * 3);
  74719. var i0 = indices[pos + 0];
  74720. var i1 = indices[pos + 1];
  74721. var i2 = indices[pos + 2];
  74722. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  74723. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  74724. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  74725. var triangle = new DecimationTriangle([v0, v1, v2]);
  74726. triangle.originalOffset = pos;
  74727. _this.triangles.push(triangle);
  74728. };
  74729. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  74730. _this.init(callback);
  74731. });
  74732. });
  74733. };
  74734. QuadraticErrorSimplification.prototype.init = function (callback) {
  74735. var _this = this;
  74736. var triangleInit1 = function (i) {
  74737. var t = _this.triangles[i];
  74738. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  74739. for (var j = 0; j < 3; j++) {
  74740. 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))));
  74741. }
  74742. };
  74743. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  74744. var triangleInit2 = function (i) {
  74745. var t = _this.triangles[i];
  74746. for (var j = 0; j < 3; ++j) {
  74747. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  74748. }
  74749. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  74750. };
  74751. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  74752. callback();
  74753. });
  74754. });
  74755. };
  74756. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  74757. var newTriangles = [];
  74758. var i;
  74759. for (i = 0; i < this.vertices.length; ++i) {
  74760. this.vertices[i].triangleCount = 0;
  74761. }
  74762. var t;
  74763. var j;
  74764. for (i = 0; i < this.triangles.length; ++i) {
  74765. if (!this.triangles[i].deleted) {
  74766. t = this.triangles[i];
  74767. for (j = 0; j < 3; ++j) {
  74768. t.vertices[j].triangleCount = 1;
  74769. }
  74770. newTriangles.push(t);
  74771. }
  74772. }
  74773. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  74774. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  74775. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  74776. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  74777. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  74778. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  74779. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  74780. var vertexCount = 0;
  74781. for (i = 0; i < this.vertices.length; ++i) {
  74782. var vertex = this.vertices[i];
  74783. vertex.id = vertexCount;
  74784. if (vertex.triangleCount) {
  74785. vertex.originalOffsets.forEach(function (originalOffset) {
  74786. if (!normalData) {
  74787. return;
  74788. }
  74789. newPositionData.push(vertex.position.x);
  74790. newPositionData.push(vertex.position.y);
  74791. newPositionData.push(vertex.position.z);
  74792. newNormalData.push(normalData[originalOffset * 3]);
  74793. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  74794. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  74795. if (uvs && uvs.length) {
  74796. newUVsData.push(uvs[(originalOffset * 2)]);
  74797. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  74798. }
  74799. else if (colorsData && colorsData.length) {
  74800. newColorsData.push(colorsData[(originalOffset * 4)]);
  74801. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  74802. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  74803. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  74804. }
  74805. ++vertexCount;
  74806. });
  74807. }
  74808. }
  74809. var startingIndex = this._reconstructedMesh.getTotalIndices();
  74810. var startingVertex = this._reconstructedMesh.getTotalVertices();
  74811. var submeshesArray = this._reconstructedMesh.subMeshes;
  74812. this._reconstructedMesh.subMeshes = [];
  74813. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  74814. var originalIndices = this._mesh.getIndices();
  74815. for (i = 0; i < newTriangles.length; ++i) {
  74816. t = newTriangles[i]; //now get the new referencing point for each vertex
  74817. [0, 1, 2].forEach(function (idx) {
  74818. var id = originalIndices[t.originalOffset + idx];
  74819. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  74820. if (offset < 0)
  74821. offset = 0;
  74822. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  74823. });
  74824. }
  74825. //overwriting the old vertex buffers and indices.
  74826. this._reconstructedMesh.setIndices(newIndicesArray);
  74827. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  74828. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  74829. if (newUVsData.length > 0)
  74830. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  74831. if (newColorsData.length > 0)
  74832. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  74833. //create submesh
  74834. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  74835. if (submeshIndex > 0) {
  74836. this._reconstructedMesh.subMeshes = [];
  74837. submeshesArray.forEach(function (submesh) {
  74838. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  74839. });
  74840. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  74841. }
  74842. };
  74843. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  74844. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  74845. this._reconstructedMesh.material = this._mesh.material;
  74846. this._reconstructedMesh.parent = this._mesh.parent;
  74847. this._reconstructedMesh.isVisible = false;
  74848. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  74849. };
  74850. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  74851. for (var i = 0; i < vertex1.triangleCount; ++i) {
  74852. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  74853. if (t.deleted)
  74854. continue;
  74855. var s = this.references[vertex1.triangleStart + i].vertexId;
  74856. var v1 = t.vertices[(s + 1) % 3];
  74857. var v2 = t.vertices[(s + 2) % 3];
  74858. if ((v1 === vertex2 || v2 === vertex2)) {
  74859. deletedArray[i] = true;
  74860. delTr.push(t);
  74861. continue;
  74862. }
  74863. var d1 = v1.position.subtract(point);
  74864. d1 = d1.normalize();
  74865. var d2 = v2.position.subtract(point);
  74866. d2 = d2.normalize();
  74867. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  74868. return true;
  74869. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  74870. deletedArray[i] = false;
  74871. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  74872. return true;
  74873. }
  74874. return false;
  74875. };
  74876. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  74877. var newDeleted = deletedTriangles;
  74878. for (var i = 0; i < vertex.triangleCount; ++i) {
  74879. var ref = this.references[vertex.triangleStart + i];
  74880. var t = this.triangles[ref.triangleId];
  74881. if (t.deleted)
  74882. continue;
  74883. if (deletedArray[i] && t.deletePending) {
  74884. t.deleted = true;
  74885. newDeleted++;
  74886. continue;
  74887. }
  74888. t.vertices[ref.vertexId] = origVertex;
  74889. t.isDirty = true;
  74890. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  74891. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  74892. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  74893. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  74894. this.references.push(ref);
  74895. }
  74896. return newDeleted;
  74897. };
  74898. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  74899. for (var i = 0; i < this.vertices.length; ++i) {
  74900. var vCount = [];
  74901. var vId = [];
  74902. var v = this.vertices[i];
  74903. var j;
  74904. for (j = 0; j < v.triangleCount; ++j) {
  74905. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  74906. for (var ii = 0; ii < 3; ii++) {
  74907. var ofs = 0;
  74908. var vv = triangle.vertices[ii];
  74909. while (ofs < vCount.length) {
  74910. if (vId[ofs] === vv.id)
  74911. break;
  74912. ++ofs;
  74913. }
  74914. if (ofs === vCount.length) {
  74915. vCount.push(1);
  74916. vId.push(vv.id);
  74917. }
  74918. else {
  74919. vCount[ofs]++;
  74920. }
  74921. }
  74922. }
  74923. for (j = 0; j < vCount.length; ++j) {
  74924. if (vCount[j] === 1) {
  74925. this.vertices[vId[j]].isBorder = true;
  74926. }
  74927. else {
  74928. this.vertices[vId[j]].isBorder = false;
  74929. }
  74930. }
  74931. }
  74932. };
  74933. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  74934. if (identifyBorders === void 0) { identifyBorders = false; }
  74935. var i;
  74936. if (!identifyBorders) {
  74937. var newTrianglesVector = [];
  74938. for (i = 0; i < this.triangles.length; ++i) {
  74939. if (!this.triangles[i].deleted) {
  74940. newTrianglesVector.push(this.triangles[i]);
  74941. }
  74942. }
  74943. this.triangles = newTrianglesVector;
  74944. }
  74945. for (i = 0; i < this.vertices.length; ++i) {
  74946. this.vertices[i].triangleCount = 0;
  74947. this.vertices[i].triangleStart = 0;
  74948. }
  74949. var t;
  74950. var j;
  74951. var v;
  74952. for (i = 0; i < this.triangles.length; ++i) {
  74953. t = this.triangles[i];
  74954. for (j = 0; j < 3; ++j) {
  74955. v = t.vertices[j];
  74956. v.triangleCount++;
  74957. }
  74958. }
  74959. var tStart = 0;
  74960. for (i = 0; i < this.vertices.length; ++i) {
  74961. this.vertices[i].triangleStart = tStart;
  74962. tStart += this.vertices[i].triangleCount;
  74963. this.vertices[i].triangleCount = 0;
  74964. }
  74965. var newReferences = new Array(this.triangles.length * 3);
  74966. for (i = 0; i < this.triangles.length; ++i) {
  74967. t = this.triangles[i];
  74968. for (j = 0; j < 3; ++j) {
  74969. v = t.vertices[j];
  74970. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  74971. v.triangleCount++;
  74972. }
  74973. }
  74974. this.references = newReferences;
  74975. if (identifyBorders) {
  74976. this.identifyBorder();
  74977. }
  74978. };
  74979. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  74980. var x = point.x;
  74981. var y = point.y;
  74982. var z = point.z;
  74983. 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
  74984. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  74985. };
  74986. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  74987. var q = vertex1.q.add(vertex2.q);
  74988. var border = vertex1.isBorder && vertex2.isBorder;
  74989. var error = 0;
  74990. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  74991. if (qDet !== 0 && !border) {
  74992. if (!pointResult) {
  74993. pointResult = BABYLON.Vector3.Zero();
  74994. }
  74995. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  74996. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  74997. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  74998. error = this.vertexError(q, pointResult);
  74999. }
  75000. else {
  75001. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  75002. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  75003. var error1 = this.vertexError(q, vertex1.position);
  75004. var error2 = this.vertexError(q, vertex2.position);
  75005. var error3 = this.vertexError(q, p3);
  75006. error = Math.min(error1, error2, error3);
  75007. if (error === error1) {
  75008. if (pointResult) {
  75009. pointResult.copyFrom(vertex1.position);
  75010. }
  75011. }
  75012. else if (error === error2) {
  75013. if (pointResult) {
  75014. pointResult.copyFrom(vertex2.position);
  75015. }
  75016. }
  75017. else {
  75018. if (pointResult) {
  75019. pointResult.copyFrom(p3);
  75020. }
  75021. }
  75022. }
  75023. return error;
  75024. };
  75025. return QuadraticErrorSimplification;
  75026. }());
  75027. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  75028. })(BABYLON || (BABYLON = {}));
  75029. //# sourceMappingURL=babylon.meshSimplification.js.map
  75030. var BABYLON;
  75031. (function (BABYLON) {
  75032. var Internals;
  75033. (function (Internals) {
  75034. var MeshLODLevel = /** @class */ (function () {
  75035. function MeshLODLevel(distance, mesh) {
  75036. this.distance = distance;
  75037. this.mesh = mesh;
  75038. }
  75039. return MeshLODLevel;
  75040. }());
  75041. Internals.MeshLODLevel = MeshLODLevel;
  75042. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  75043. })(BABYLON || (BABYLON = {}));
  75044. //# sourceMappingURL=babylon.meshLODLevel.js.map
  75045. var BABYLON;
  75046. (function (BABYLON) {
  75047. // Standard optimizations
  75048. var SceneOptimization = /** @class */ (function () {
  75049. function SceneOptimization(priority) {
  75050. if (priority === void 0) { priority = 0; }
  75051. this.priority = priority;
  75052. this.apply = function (scene) {
  75053. return true; // Return true if everything that can be done was applied
  75054. };
  75055. }
  75056. return SceneOptimization;
  75057. }());
  75058. BABYLON.SceneOptimization = SceneOptimization;
  75059. var TextureOptimization = /** @class */ (function (_super) {
  75060. __extends(TextureOptimization, _super);
  75061. function TextureOptimization(priority, maximumSize) {
  75062. if (priority === void 0) { priority = 0; }
  75063. if (maximumSize === void 0) { maximumSize = 1024; }
  75064. var _this = _super.call(this, priority) || this;
  75065. _this.priority = priority;
  75066. _this.maximumSize = maximumSize;
  75067. _this.apply = function (scene) {
  75068. var allDone = true;
  75069. for (var index = 0; index < scene.textures.length; index++) {
  75070. var texture = scene.textures[index];
  75071. if (!texture.canRescale || texture.getContext) {
  75072. continue;
  75073. }
  75074. var currentSize = texture.getSize();
  75075. var maxDimension = Math.max(currentSize.width, currentSize.height);
  75076. if (maxDimension > _this.maximumSize) {
  75077. texture.scale(0.5);
  75078. allDone = false;
  75079. }
  75080. }
  75081. return allDone;
  75082. };
  75083. return _this;
  75084. }
  75085. return TextureOptimization;
  75086. }(SceneOptimization));
  75087. BABYLON.TextureOptimization = TextureOptimization;
  75088. var HardwareScalingOptimization = /** @class */ (function (_super) {
  75089. __extends(HardwareScalingOptimization, _super);
  75090. function HardwareScalingOptimization(priority, maximumScale) {
  75091. if (priority === void 0) { priority = 0; }
  75092. if (maximumScale === void 0) { maximumScale = 2; }
  75093. var _this = _super.call(this, priority) || this;
  75094. _this.priority = priority;
  75095. _this.maximumScale = maximumScale;
  75096. _this._currentScale = 1;
  75097. _this.apply = function (scene) {
  75098. _this._currentScale++;
  75099. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  75100. return _this._currentScale >= _this.maximumScale;
  75101. };
  75102. return _this;
  75103. }
  75104. return HardwareScalingOptimization;
  75105. }(SceneOptimization));
  75106. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  75107. var ShadowsOptimization = /** @class */ (function (_super) {
  75108. __extends(ShadowsOptimization, _super);
  75109. function ShadowsOptimization() {
  75110. var _this = _super !== null && _super.apply(this, arguments) || this;
  75111. _this.apply = function (scene) {
  75112. scene.shadowsEnabled = false;
  75113. return true;
  75114. };
  75115. return _this;
  75116. }
  75117. return ShadowsOptimization;
  75118. }(SceneOptimization));
  75119. BABYLON.ShadowsOptimization = ShadowsOptimization;
  75120. var PostProcessesOptimization = /** @class */ (function (_super) {
  75121. __extends(PostProcessesOptimization, _super);
  75122. function PostProcessesOptimization() {
  75123. var _this = _super !== null && _super.apply(this, arguments) || this;
  75124. _this.apply = function (scene) {
  75125. scene.postProcessesEnabled = false;
  75126. return true;
  75127. };
  75128. return _this;
  75129. }
  75130. return PostProcessesOptimization;
  75131. }(SceneOptimization));
  75132. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  75133. var LensFlaresOptimization = /** @class */ (function (_super) {
  75134. __extends(LensFlaresOptimization, _super);
  75135. function LensFlaresOptimization() {
  75136. var _this = _super !== null && _super.apply(this, arguments) || this;
  75137. _this.apply = function (scene) {
  75138. scene.lensFlaresEnabled = false;
  75139. return true;
  75140. };
  75141. return _this;
  75142. }
  75143. return LensFlaresOptimization;
  75144. }(SceneOptimization));
  75145. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  75146. var ParticlesOptimization = /** @class */ (function (_super) {
  75147. __extends(ParticlesOptimization, _super);
  75148. function ParticlesOptimization() {
  75149. var _this = _super !== null && _super.apply(this, arguments) || this;
  75150. _this.apply = function (scene) {
  75151. scene.particlesEnabled = false;
  75152. return true;
  75153. };
  75154. return _this;
  75155. }
  75156. return ParticlesOptimization;
  75157. }(SceneOptimization));
  75158. BABYLON.ParticlesOptimization = ParticlesOptimization;
  75159. var RenderTargetsOptimization = /** @class */ (function (_super) {
  75160. __extends(RenderTargetsOptimization, _super);
  75161. function RenderTargetsOptimization() {
  75162. var _this = _super !== null && _super.apply(this, arguments) || this;
  75163. _this.apply = function (scene) {
  75164. scene.renderTargetsEnabled = false;
  75165. return true;
  75166. };
  75167. return _this;
  75168. }
  75169. return RenderTargetsOptimization;
  75170. }(SceneOptimization));
  75171. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  75172. var MergeMeshesOptimization = /** @class */ (function (_super) {
  75173. __extends(MergeMeshesOptimization, _super);
  75174. function MergeMeshesOptimization() {
  75175. var _this = _super !== null && _super.apply(this, arguments) || this;
  75176. _this._canBeMerged = function (abstractMesh) {
  75177. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  75178. return false;
  75179. }
  75180. var mesh = abstractMesh;
  75181. if (!mesh.isVisible || !mesh.isEnabled()) {
  75182. return false;
  75183. }
  75184. if (mesh.instances.length > 0) {
  75185. return false;
  75186. }
  75187. if (mesh.skeleton || mesh.hasLODLevels) {
  75188. return false;
  75189. }
  75190. if (mesh.parent) {
  75191. return false;
  75192. }
  75193. return true;
  75194. };
  75195. _this.apply = function (scene, updateSelectionTree) {
  75196. var globalPool = scene.meshes.slice(0);
  75197. var globalLength = globalPool.length;
  75198. for (var index = 0; index < globalLength; index++) {
  75199. var currentPool = new Array();
  75200. var current = globalPool[index];
  75201. // Checks
  75202. if (!_this._canBeMerged(current)) {
  75203. continue;
  75204. }
  75205. currentPool.push(current);
  75206. // Find compatible meshes
  75207. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  75208. var otherMesh = globalPool[subIndex];
  75209. if (!_this._canBeMerged(otherMesh)) {
  75210. continue;
  75211. }
  75212. if (otherMesh.material !== current.material) {
  75213. continue;
  75214. }
  75215. if (otherMesh.checkCollisions !== current.checkCollisions) {
  75216. continue;
  75217. }
  75218. currentPool.push(otherMesh);
  75219. globalLength--;
  75220. globalPool.splice(subIndex, 1);
  75221. subIndex--;
  75222. }
  75223. if (currentPool.length < 2) {
  75224. continue;
  75225. }
  75226. // Merge meshes
  75227. BABYLON.Mesh.MergeMeshes(currentPool);
  75228. }
  75229. if (updateSelectionTree != undefined) {
  75230. if (updateSelectionTree) {
  75231. scene.createOrUpdateSelectionOctree();
  75232. }
  75233. }
  75234. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  75235. scene.createOrUpdateSelectionOctree();
  75236. }
  75237. return true;
  75238. };
  75239. return _this;
  75240. }
  75241. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  75242. get: function () {
  75243. return MergeMeshesOptimization._UpdateSelectionTree;
  75244. },
  75245. set: function (value) {
  75246. MergeMeshesOptimization._UpdateSelectionTree = value;
  75247. },
  75248. enumerable: true,
  75249. configurable: true
  75250. });
  75251. MergeMeshesOptimization._UpdateSelectionTree = false;
  75252. return MergeMeshesOptimization;
  75253. }(SceneOptimization));
  75254. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  75255. // Options
  75256. var SceneOptimizerOptions = /** @class */ (function () {
  75257. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  75258. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  75259. if (trackerDuration === void 0) { trackerDuration = 2000; }
  75260. this.targetFrameRate = targetFrameRate;
  75261. this.trackerDuration = trackerDuration;
  75262. this.optimizations = new Array();
  75263. }
  75264. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  75265. var result = new SceneOptimizerOptions(targetFrameRate);
  75266. var priority = 0;
  75267. result.optimizations.push(new MergeMeshesOptimization(priority));
  75268. result.optimizations.push(new ShadowsOptimization(priority));
  75269. result.optimizations.push(new LensFlaresOptimization(priority));
  75270. // Next priority
  75271. priority++;
  75272. result.optimizations.push(new PostProcessesOptimization(priority));
  75273. result.optimizations.push(new ParticlesOptimization(priority));
  75274. // Next priority
  75275. priority++;
  75276. result.optimizations.push(new TextureOptimization(priority, 1024));
  75277. return result;
  75278. };
  75279. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  75280. var result = new SceneOptimizerOptions(targetFrameRate);
  75281. var priority = 0;
  75282. result.optimizations.push(new MergeMeshesOptimization(priority));
  75283. result.optimizations.push(new ShadowsOptimization(priority));
  75284. result.optimizations.push(new LensFlaresOptimization(priority));
  75285. // Next priority
  75286. priority++;
  75287. result.optimizations.push(new PostProcessesOptimization(priority));
  75288. result.optimizations.push(new ParticlesOptimization(priority));
  75289. // Next priority
  75290. priority++;
  75291. result.optimizations.push(new TextureOptimization(priority, 512));
  75292. // Next priority
  75293. priority++;
  75294. result.optimizations.push(new RenderTargetsOptimization(priority));
  75295. // Next priority
  75296. priority++;
  75297. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  75298. return result;
  75299. };
  75300. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  75301. var result = new SceneOptimizerOptions(targetFrameRate);
  75302. var priority = 0;
  75303. result.optimizations.push(new MergeMeshesOptimization(priority));
  75304. result.optimizations.push(new ShadowsOptimization(priority));
  75305. result.optimizations.push(new LensFlaresOptimization(priority));
  75306. // Next priority
  75307. priority++;
  75308. result.optimizations.push(new PostProcessesOptimization(priority));
  75309. result.optimizations.push(new ParticlesOptimization(priority));
  75310. // Next priority
  75311. priority++;
  75312. result.optimizations.push(new TextureOptimization(priority, 256));
  75313. // Next priority
  75314. priority++;
  75315. result.optimizations.push(new RenderTargetsOptimization(priority));
  75316. // Next priority
  75317. priority++;
  75318. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  75319. return result;
  75320. };
  75321. return SceneOptimizerOptions;
  75322. }());
  75323. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  75324. // Scene optimizer tool
  75325. var SceneOptimizer = /** @class */ (function () {
  75326. function SceneOptimizer() {
  75327. }
  75328. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  75329. // TODO: add an epsilon
  75330. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  75331. if (onSuccess) {
  75332. onSuccess();
  75333. }
  75334. return;
  75335. }
  75336. // Apply current level of optimizations
  75337. var allDone = true;
  75338. var noOptimizationApplied = true;
  75339. for (var index = 0; index < options.optimizations.length; index++) {
  75340. var optimization = options.optimizations[index];
  75341. if (optimization.priority === currentPriorityLevel) {
  75342. noOptimizationApplied = false;
  75343. allDone = allDone && optimization.apply(scene);
  75344. }
  75345. }
  75346. // If no optimization was applied, this is a failure :(
  75347. if (noOptimizationApplied) {
  75348. if (onFailure) {
  75349. onFailure();
  75350. }
  75351. return;
  75352. }
  75353. // If all optimizations were done, move to next level
  75354. if (allDone) {
  75355. currentPriorityLevel++;
  75356. }
  75357. // Let's the system running for a specific amount of time before checking FPS
  75358. scene.executeWhenReady(function () {
  75359. setTimeout(function () {
  75360. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  75361. }, options.trackerDuration);
  75362. });
  75363. };
  75364. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  75365. if (!options) {
  75366. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  75367. }
  75368. // Let's the system running for a specific amount of time before checking FPS
  75369. scene.executeWhenReady(function () {
  75370. setTimeout(function () {
  75371. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  75372. }, options.trackerDuration);
  75373. });
  75374. };
  75375. return SceneOptimizer;
  75376. }());
  75377. BABYLON.SceneOptimizer = SceneOptimizer;
  75378. })(BABYLON || (BABYLON = {}));
  75379. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  75380. var BABYLON;
  75381. (function (BABYLON) {
  75382. var OutlineRenderer = /** @class */ (function () {
  75383. function OutlineRenderer(scene) {
  75384. this.zOffset = 1;
  75385. this._scene = scene;
  75386. }
  75387. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  75388. var _this = this;
  75389. if (useOverlay === void 0) { useOverlay = false; }
  75390. var scene = this._scene;
  75391. var engine = this._scene.getEngine();
  75392. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  75393. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  75394. return;
  75395. }
  75396. var mesh = subMesh.getRenderingMesh();
  75397. var material = subMesh.getMaterial();
  75398. if (!material || !scene.activeCamera) {
  75399. return;
  75400. }
  75401. engine.enableEffect(this._effect);
  75402. // Logarithmic depth
  75403. if (material.useLogarithmicDepth) {
  75404. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  75405. }
  75406. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  75407. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  75408. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  75409. // Bones
  75410. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  75411. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  75412. }
  75413. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  75414. // Alpha test
  75415. if (material && material.needAlphaTesting()) {
  75416. var alphaTexture = material.getAlphaTestTexture();
  75417. if (alphaTexture) {
  75418. this._effect.setTexture("diffuseSampler", alphaTexture);
  75419. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  75420. }
  75421. }
  75422. engine.setZOffset(-this.zOffset);
  75423. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  75424. engine.setZOffset(0);
  75425. };
  75426. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  75427. var defines = [];
  75428. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  75429. var mesh = subMesh.getMesh();
  75430. var material = subMesh.getMaterial();
  75431. if (material) {
  75432. // Alpha test
  75433. if (material.needAlphaTesting()) {
  75434. defines.push("#define ALPHATEST");
  75435. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  75436. attribs.push(BABYLON.VertexBuffer.UVKind);
  75437. defines.push("#define UV1");
  75438. }
  75439. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  75440. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  75441. defines.push("#define UV2");
  75442. }
  75443. }
  75444. //Logarithmic depth
  75445. if (material.useLogarithmicDepth) {
  75446. defines.push("#define LOGARITHMICDEPTH");
  75447. }
  75448. }
  75449. // Bones
  75450. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  75451. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  75452. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  75453. if (mesh.numBoneInfluencers > 4) {
  75454. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  75455. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  75456. }
  75457. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  75458. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  75459. }
  75460. else {
  75461. defines.push("#define NUM_BONE_INFLUENCERS 0");
  75462. }
  75463. // Instances
  75464. if (useInstances) {
  75465. defines.push("#define INSTANCES");
  75466. attribs.push("world0");
  75467. attribs.push("world1");
  75468. attribs.push("world2");
  75469. attribs.push("world3");
  75470. }
  75471. // Get correct effect
  75472. var join = defines.join("\n");
  75473. if (this._cachedDefines !== join) {
  75474. this._cachedDefines = join;
  75475. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  75476. }
  75477. return this._effect.isReady();
  75478. };
  75479. return OutlineRenderer;
  75480. }());
  75481. BABYLON.OutlineRenderer = OutlineRenderer;
  75482. })(BABYLON || (BABYLON = {}));
  75483. //# sourceMappingURL=babylon.outlineRenderer.js.map
  75484. var BABYLON;
  75485. (function (BABYLON) {
  75486. var FaceAdjacencies = /** @class */ (function () {
  75487. function FaceAdjacencies() {
  75488. this.edges = new Array();
  75489. this.edgesConnectedCount = 0;
  75490. }
  75491. return FaceAdjacencies;
  75492. }());
  75493. var EdgesRenderer = /** @class */ (function () {
  75494. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  75495. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  75496. if (epsilon === void 0) { epsilon = 0.95; }
  75497. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  75498. this.edgesWidthScalerForOrthographic = 1000.0;
  75499. this.edgesWidthScalerForPerspective = 50.0;
  75500. this._linesPositions = new Array();
  75501. this._linesNormals = new Array();
  75502. this._linesIndices = new Array();
  75503. this._buffers = {};
  75504. this._checkVerticesInsteadOfIndices = false;
  75505. this._source = source;
  75506. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  75507. this._epsilon = epsilon;
  75508. this._prepareRessources();
  75509. this._generateEdgesLines();
  75510. }
  75511. EdgesRenderer.prototype._prepareRessources = function () {
  75512. if (this._lineShader) {
  75513. return;
  75514. }
  75515. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  75516. attributes: ["position", "normal"],
  75517. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  75518. });
  75519. this._lineShader.disableDepthWrite = true;
  75520. this._lineShader.backFaceCulling = false;
  75521. };
  75522. EdgesRenderer.prototype._rebuild = function () {
  75523. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  75524. if (buffer) {
  75525. buffer._rebuild();
  75526. }
  75527. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  75528. if (buffer) {
  75529. buffer._rebuild();
  75530. }
  75531. var scene = this._source.getScene();
  75532. var engine = scene.getEngine();
  75533. this._ib = engine.createIndexBuffer(this._linesIndices);
  75534. };
  75535. EdgesRenderer.prototype.dispose = function () {
  75536. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  75537. if (buffer) {
  75538. buffer.dispose();
  75539. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  75540. }
  75541. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  75542. if (buffer) {
  75543. buffer.dispose();
  75544. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  75545. }
  75546. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  75547. this._lineShader.dispose();
  75548. };
  75549. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  75550. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  75551. return 0;
  75552. }
  75553. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  75554. return 1;
  75555. }
  75556. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  75557. return 2;
  75558. }
  75559. return -1;
  75560. };
  75561. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  75562. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  75563. return 0;
  75564. }
  75565. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  75566. return 1;
  75567. }
  75568. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  75569. return 2;
  75570. }
  75571. return -1;
  75572. };
  75573. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  75574. var needToCreateLine;
  75575. if (edge === undefined) {
  75576. needToCreateLine = true;
  75577. }
  75578. else {
  75579. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  75580. needToCreateLine = dotProduct < this._epsilon;
  75581. }
  75582. if (needToCreateLine) {
  75583. var offset = this._linesPositions.length / 3;
  75584. var normal = p0.subtract(p1);
  75585. normal.normalize();
  75586. // Positions
  75587. this._linesPositions.push(p0.x);
  75588. this._linesPositions.push(p0.y);
  75589. this._linesPositions.push(p0.z);
  75590. this._linesPositions.push(p0.x);
  75591. this._linesPositions.push(p0.y);
  75592. this._linesPositions.push(p0.z);
  75593. this._linesPositions.push(p1.x);
  75594. this._linesPositions.push(p1.y);
  75595. this._linesPositions.push(p1.z);
  75596. this._linesPositions.push(p1.x);
  75597. this._linesPositions.push(p1.y);
  75598. this._linesPositions.push(p1.z);
  75599. // Normals
  75600. this._linesNormals.push(p1.x);
  75601. this._linesNormals.push(p1.y);
  75602. this._linesNormals.push(p1.z);
  75603. this._linesNormals.push(-1);
  75604. this._linesNormals.push(p1.x);
  75605. this._linesNormals.push(p1.y);
  75606. this._linesNormals.push(p1.z);
  75607. this._linesNormals.push(1);
  75608. this._linesNormals.push(p0.x);
  75609. this._linesNormals.push(p0.y);
  75610. this._linesNormals.push(p0.z);
  75611. this._linesNormals.push(-1);
  75612. this._linesNormals.push(p0.x);
  75613. this._linesNormals.push(p0.y);
  75614. this._linesNormals.push(p0.z);
  75615. this._linesNormals.push(1);
  75616. // Indices
  75617. this._linesIndices.push(offset);
  75618. this._linesIndices.push(offset + 1);
  75619. this._linesIndices.push(offset + 2);
  75620. this._linesIndices.push(offset);
  75621. this._linesIndices.push(offset + 2);
  75622. this._linesIndices.push(offset + 3);
  75623. }
  75624. };
  75625. EdgesRenderer.prototype._generateEdgesLines = function () {
  75626. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  75627. var indices = this._source.getIndices();
  75628. if (!indices || !positions) {
  75629. return;
  75630. }
  75631. // First let's find adjacencies
  75632. var adjacencies = new Array();
  75633. var faceNormals = new Array();
  75634. var index;
  75635. var faceAdjacencies;
  75636. // Prepare faces
  75637. for (index = 0; index < indices.length; index += 3) {
  75638. faceAdjacencies = new FaceAdjacencies();
  75639. var p0Index = indices[index];
  75640. var p1Index = indices[index + 1];
  75641. var p2Index = indices[index + 2];
  75642. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  75643. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  75644. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  75645. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  75646. faceNormal.normalize();
  75647. faceNormals.push(faceNormal);
  75648. adjacencies.push(faceAdjacencies);
  75649. }
  75650. // Scan
  75651. for (index = 0; index < adjacencies.length; index++) {
  75652. faceAdjacencies = adjacencies[index];
  75653. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  75654. var otherFaceAdjacencies = adjacencies[otherIndex];
  75655. if (faceAdjacencies.edgesConnectedCount === 3) {
  75656. break;
  75657. }
  75658. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  75659. continue;
  75660. }
  75661. var otherP0 = indices[otherIndex * 3];
  75662. var otherP1 = indices[otherIndex * 3 + 1];
  75663. var otherP2 = indices[otherIndex * 3 + 2];
  75664. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  75665. var otherEdgeIndex = 0;
  75666. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  75667. continue;
  75668. }
  75669. switch (edgeIndex) {
  75670. case 0:
  75671. if (this._checkVerticesInsteadOfIndices) {
  75672. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  75673. }
  75674. else {
  75675. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  75676. }
  75677. break;
  75678. case 1:
  75679. if (this._checkVerticesInsteadOfIndices) {
  75680. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  75681. }
  75682. else {
  75683. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  75684. }
  75685. break;
  75686. case 2:
  75687. if (this._checkVerticesInsteadOfIndices) {
  75688. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  75689. }
  75690. else {
  75691. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  75692. }
  75693. break;
  75694. }
  75695. if (otherEdgeIndex === -1) {
  75696. continue;
  75697. }
  75698. faceAdjacencies.edges[edgeIndex] = otherIndex;
  75699. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  75700. faceAdjacencies.edgesConnectedCount++;
  75701. otherFaceAdjacencies.edgesConnectedCount++;
  75702. if (faceAdjacencies.edgesConnectedCount === 3) {
  75703. break;
  75704. }
  75705. }
  75706. }
  75707. }
  75708. // Create lines
  75709. for (index = 0; index < adjacencies.length; index++) {
  75710. // 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
  75711. var current = adjacencies[index];
  75712. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  75713. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  75714. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  75715. }
  75716. // Merge into a single mesh
  75717. var engine = this._source.getScene().getEngine();
  75718. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  75719. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  75720. this._ib = engine.createIndexBuffer(this._linesIndices);
  75721. this._indicesCount = this._linesIndices.length;
  75722. };
  75723. EdgesRenderer.prototype.render = function () {
  75724. var scene = this._source.getScene();
  75725. if (!this._lineShader.isReady() || !scene.activeCamera) {
  75726. return;
  75727. }
  75728. var engine = scene.getEngine();
  75729. this._lineShader._preBind();
  75730. // VBOs
  75731. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  75732. scene.resetCachedMaterial();
  75733. this._lineShader.setColor4("color", this._source.edgesColor);
  75734. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  75735. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  75736. }
  75737. else {
  75738. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  75739. }
  75740. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  75741. this._lineShader.bind(this._source.getWorldMatrix());
  75742. // Draw order
  75743. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  75744. this._lineShader.unbind();
  75745. engine.setDepthWrite(true);
  75746. };
  75747. return EdgesRenderer;
  75748. }());
  75749. BABYLON.EdgesRenderer = EdgesRenderer;
  75750. })(BABYLON || (BABYLON = {}));
  75751. //# sourceMappingURL=babylon.edgesRenderer.js.map
  75752. var BABYLON;
  75753. (function (BABYLON) {
  75754. /**
  75755. * Special Glow Blur post process only blurring the alpha channel
  75756. * It enforces keeping the most luminous color in the color channel.
  75757. */
  75758. var GlowBlurPostProcess = /** @class */ (function (_super) {
  75759. __extends(GlowBlurPostProcess, _super);
  75760. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  75761. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  75762. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  75763. _this.direction = direction;
  75764. _this.kernel = kernel;
  75765. _this.onApplyObservable.add(function (effect) {
  75766. effect.setFloat2("screenSize", _this.width, _this.height);
  75767. effect.setVector2("direction", _this.direction);
  75768. effect.setFloat("blurWidth", _this.kernel);
  75769. });
  75770. return _this;
  75771. }
  75772. return GlowBlurPostProcess;
  75773. }(BABYLON.PostProcess));
  75774. /**
  75775. * The highlight layer Helps adding a glow effect around a mesh.
  75776. *
  75777. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  75778. * glowy meshes to your scene.
  75779. *
  75780. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  75781. */
  75782. var HighlightLayer = /** @class */ (function () {
  75783. /**
  75784. * Instantiates a new highlight Layer and references it to the scene..
  75785. * @param name The name of the layer
  75786. * @param scene The scene to use the layer in
  75787. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  75788. */
  75789. function HighlightLayer(name, scene, options) {
  75790. this.name = name;
  75791. this._vertexBuffers = {};
  75792. this._mainTextureDesiredSize = { width: 0, height: 0 };
  75793. this._meshes = {};
  75794. this._maxSize = 0;
  75795. this._shouldRender = false;
  75796. this._instanceGlowingMeshStencilReference = HighlightLayer.glowingMeshStencilReference++;
  75797. this._excludedMeshes = {};
  75798. /**
  75799. * Specifies whether or not the inner glow is ACTIVE in the layer.
  75800. */
  75801. this.innerGlow = true;
  75802. /**
  75803. * Specifies whether or not the outer glow is ACTIVE in the layer.
  75804. */
  75805. this.outerGlow = true;
  75806. /**
  75807. * Specifies wether the highlight layer is enabled or not.
  75808. */
  75809. this.isEnabled = true;
  75810. /**
  75811. * An event triggered when the highlight layer has been disposed.
  75812. * @type {BABYLON.Observable}
  75813. */
  75814. this.onDisposeObservable = new BABYLON.Observable();
  75815. /**
  75816. * An event triggered when the highlight layer is about rendering the main texture with the glowy parts.
  75817. * @type {BABYLON.Observable}
  75818. */
  75819. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  75820. /**
  75821. * An event triggered when the highlight layer is being blurred.
  75822. * @type {BABYLON.Observable}
  75823. */
  75824. this.onBeforeBlurObservable = new BABYLON.Observable();
  75825. /**
  75826. * An event triggered when the highlight layer has been blurred.
  75827. * @type {BABYLON.Observable}
  75828. */
  75829. this.onAfterBlurObservable = new BABYLON.Observable();
  75830. /**
  75831. * An event triggered when the glowing blurred texture is being merged in the scene.
  75832. * @type {BABYLON.Observable}
  75833. */
  75834. this.onBeforeComposeObservable = new BABYLON.Observable();
  75835. /**
  75836. * An event triggered when the glowing blurred texture has been merged in the scene.
  75837. * @type {BABYLON.Observable}
  75838. */
  75839. this.onAfterComposeObservable = new BABYLON.Observable();
  75840. /**
  75841. * An event triggered when the highlight layer changes its size.
  75842. * @type {BABYLON.Observable}
  75843. */
  75844. this.onSizeChangedObservable = new BABYLON.Observable();
  75845. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  75846. var engine = scene.getEngine();
  75847. this._engine = engine;
  75848. this._maxSize = this._engine.getCaps().maxTextureSize;
  75849. this._scene.highlightLayers.push(this);
  75850. // Warn on stencil.
  75851. if (!this._engine.isStencilEnable) {
  75852. 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 }");
  75853. }
  75854. // Adapt options
  75855. this._options = options || {
  75856. mainTextureRatio: 0.5,
  75857. blurTextureSizeRatio: 0.5,
  75858. blurHorizontalSize: 1.0,
  75859. blurVerticalSize: 1.0,
  75860. alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE,
  75861. camera: null
  75862. };
  75863. this._options.mainTextureRatio = this._options.mainTextureRatio || 0.5;
  75864. this._options.blurTextureSizeRatio = this._options.blurTextureSizeRatio || 1.0;
  75865. this._options.blurHorizontalSize = this._options.blurHorizontalSize || 1;
  75866. this._options.blurVerticalSize = this._options.blurVerticalSize || 1;
  75867. this._options.alphaBlendingMode = this._options.alphaBlendingMode || BABYLON.Engine.ALPHA_COMBINE;
  75868. // VBO
  75869. var vertices = [];
  75870. vertices.push(1, 1);
  75871. vertices.push(-1, 1);
  75872. vertices.push(-1, -1);
  75873. vertices.push(1, -1);
  75874. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  75875. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  75876. this._createIndexBuffer();
  75877. // Effect
  75878. this._glowMapMergeEffect = engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], "");
  75879. // Render target
  75880. this.setMainTextureSize();
  75881. // Create Textures and post processes
  75882. this.createTextureAndPostProcesses();
  75883. }
  75884. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  75885. /**
  75886. * Gets the horizontal size of the blur.
  75887. */
  75888. get: function () {
  75889. return this._horizontalBlurPostprocess.kernel;
  75890. },
  75891. /**
  75892. * Specifies the horizontal size of the blur.
  75893. */
  75894. set: function (value) {
  75895. this._horizontalBlurPostprocess.kernel = value;
  75896. },
  75897. enumerable: true,
  75898. configurable: true
  75899. });
  75900. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  75901. /**
  75902. * Gets the vertical size of the blur.
  75903. */
  75904. get: function () {
  75905. return this._verticalBlurPostprocess.kernel;
  75906. },
  75907. /**
  75908. * Specifies the vertical size of the blur.
  75909. */
  75910. set: function (value) {
  75911. this._verticalBlurPostprocess.kernel = value;
  75912. },
  75913. enumerable: true,
  75914. configurable: true
  75915. });
  75916. Object.defineProperty(HighlightLayer.prototype, "camera", {
  75917. /**
  75918. * Gets the camera attached to the layer.
  75919. */
  75920. get: function () {
  75921. return this._options.camera;
  75922. },
  75923. enumerable: true,
  75924. configurable: true
  75925. });
  75926. HighlightLayer.prototype._createIndexBuffer = function () {
  75927. var engine = this._scene.getEngine();
  75928. // Indices
  75929. var indices = [];
  75930. indices.push(0);
  75931. indices.push(1);
  75932. indices.push(2);
  75933. indices.push(0);
  75934. indices.push(2);
  75935. indices.push(3);
  75936. this._indexBuffer = engine.createIndexBuffer(indices);
  75937. };
  75938. HighlightLayer.prototype._rebuild = function () {
  75939. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  75940. if (vb) {
  75941. vb._rebuild();
  75942. }
  75943. this._createIndexBuffer();
  75944. };
  75945. /**
  75946. * Creates the render target textures and post processes used in the highlight layer.
  75947. */
  75948. HighlightLayer.prototype.createTextureAndPostProcesses = function () {
  75949. var _this = this;
  75950. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  75951. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  75952. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  75953. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  75954. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  75955. width: this._mainTextureDesiredSize.width,
  75956. height: this._mainTextureDesiredSize.height
  75957. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  75958. this._mainTexture.activeCamera = this._options.camera;
  75959. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  75960. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  75961. this._mainTexture.anisotropicFilteringLevel = 1;
  75962. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  75963. this._mainTexture.renderParticles = false;
  75964. this._mainTexture.renderList = null;
  75965. this._mainTexture.ignoreCameraViewport = true;
  75966. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  75967. width: blurTextureWidth,
  75968. height: blurTextureHeight
  75969. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  75970. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  75971. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  75972. this._blurTexture.anisotropicFilteringLevel = 16;
  75973. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  75974. this._blurTexture.renderParticles = false;
  75975. this._blurTexture.ignoreCameraViewport = true;
  75976. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  75977. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  75978. effect.setTexture("textureSampler", _this._mainTexture);
  75979. });
  75980. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  75981. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  75982. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  75983. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  75984. });
  75985. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  75986. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  75987. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  75988. });
  75989. }
  75990. else {
  75991. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  75992. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  75993. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  75994. });
  75995. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  75996. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  75997. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  75998. });
  75999. }
  76000. this._mainTexture.onAfterUnbindObservable.add(function () {
  76001. _this.onBeforeBlurObservable.notifyObservers(_this);
  76002. var internalTexture = _this._blurTexture.getInternalTexture();
  76003. if (internalTexture) {
  76004. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._horizontalBlurPostprocess, _this._verticalBlurPostprocess], internalTexture, true);
  76005. }
  76006. _this.onAfterBlurObservable.notifyObservers(_this);
  76007. });
  76008. // Custom render function
  76009. var renderSubMesh = function (subMesh) {
  76010. if (!_this._meshes) {
  76011. return;
  76012. }
  76013. var material = subMesh.getMaterial();
  76014. var mesh = subMesh.getRenderingMesh();
  76015. var scene = _this._scene;
  76016. var engine = scene.getEngine();
  76017. if (!material) {
  76018. return;
  76019. }
  76020. // Do not block in blend mode.
  76021. if (material.needAlphaBlendingForMesh(mesh)) {
  76022. return;
  76023. }
  76024. // Culling
  76025. engine.setState(material.backFaceCulling);
  76026. // Managing instances
  76027. var batch = mesh._getInstancesRenderList(subMesh._id);
  76028. if (batch.mustReturn) {
  76029. return;
  76030. }
  76031. // Excluded Mesh
  76032. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  76033. return;
  76034. }
  76035. ;
  76036. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  76037. var highlightLayerMesh = _this._meshes[mesh.uniqueId];
  76038. var emissiveTexture = null;
  76039. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  76040. emissiveTexture = material.emissiveTexture;
  76041. }
  76042. if (_this.isReady(subMesh, hardwareInstancedRendering, emissiveTexture)) {
  76043. engine.enableEffect(_this._glowMapGenerationEffect);
  76044. mesh._bind(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  76045. _this._glowMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  76046. if (highlightLayerMesh) {
  76047. _this._glowMapGenerationEffect.setFloat4("color", highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  76048. }
  76049. else {
  76050. _this._glowMapGenerationEffect.setFloat4("color", HighlightLayer.neutralColor.r, HighlightLayer.neutralColor.g, HighlightLayer.neutralColor.b, HighlightLayer.neutralColor.a);
  76051. }
  76052. // Alpha test
  76053. if (material && material.needAlphaTesting()) {
  76054. var alphaTexture = material.getAlphaTestTexture();
  76055. if (alphaTexture) {
  76056. _this._glowMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  76057. var textureMatrix = alphaTexture.getTextureMatrix();
  76058. if (textureMatrix) {
  76059. _this._glowMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  76060. }
  76061. }
  76062. }
  76063. // Glow emissive only
  76064. if (emissiveTexture) {
  76065. _this._glowMapGenerationEffect.setTexture("emissiveSampler", emissiveTexture);
  76066. _this._glowMapGenerationEffect.setMatrix("emissiveMatrix", emissiveTexture.getTextureMatrix());
  76067. }
  76068. // Bones
  76069. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  76070. _this._glowMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  76071. }
  76072. // Draw
  76073. mesh._processRendering(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._glowMapGenerationEffect.setMatrix("world", world); });
  76074. }
  76075. else {
  76076. // Need to reset refresh rate of the shadowMap
  76077. _this._mainTexture.resetRefreshCounter();
  76078. }
  76079. };
  76080. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  76081. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  76082. var index;
  76083. var engine = _this._scene.getEngine();
  76084. if (depthOnlySubMeshes.length) {
  76085. engine.setColorWrite(false);
  76086. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  76087. renderSubMesh(depthOnlySubMeshes.data[index]);
  76088. }
  76089. engine.setColorWrite(true);
  76090. }
  76091. for (index = 0; index < opaqueSubMeshes.length; index++) {
  76092. renderSubMesh(opaqueSubMeshes.data[index]);
  76093. }
  76094. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  76095. renderSubMesh(alphaTestSubMeshes.data[index]);
  76096. }
  76097. for (index = 0; index < transparentSubMeshes.length; index++) {
  76098. renderSubMesh(transparentSubMeshes.data[index]);
  76099. }
  76100. };
  76101. this._mainTexture.onClearObservable.add(function (engine) {
  76102. engine.clear(HighlightLayer.neutralColor, true, true, true);
  76103. });
  76104. };
  76105. /**
  76106. * Checks for the readiness of the element composing the layer.
  76107. * @param subMesh the mesh to check for
  76108. * @param useInstances specify wether or not to use instances to render the mesh
  76109. * @param emissiveTexture the associated emissive texture used to generate the glow
  76110. * @return true if ready otherwise, false
  76111. */
  76112. HighlightLayer.prototype.isReady = function (subMesh, useInstances, emissiveTexture) {
  76113. var material = subMesh.getMaterial();
  76114. if (!material) {
  76115. return false;
  76116. }
  76117. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  76118. return false;
  76119. }
  76120. var defines = [];
  76121. var attribs = [BABYLON.VertexBuffer.PositionKind];
  76122. var mesh = subMesh.getMesh();
  76123. var uv1 = false;
  76124. var uv2 = false;
  76125. // Alpha test
  76126. if (material && material.needAlphaTesting()) {
  76127. var alphaTexture = material.getAlphaTestTexture();
  76128. if (alphaTexture) {
  76129. defines.push("#define ALPHATEST");
  76130. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  76131. alphaTexture.coordinatesIndex === 1) {
  76132. defines.push("#define DIFFUSEUV2");
  76133. uv2 = true;
  76134. }
  76135. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  76136. defines.push("#define DIFFUSEUV1");
  76137. uv1 = true;
  76138. }
  76139. }
  76140. }
  76141. // Emissive
  76142. if (emissiveTexture) {
  76143. defines.push("#define EMISSIVE");
  76144. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  76145. emissiveTexture.coordinatesIndex === 1) {
  76146. defines.push("#define EMISSIVEUV2");
  76147. uv2 = true;
  76148. }
  76149. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  76150. defines.push("#define EMISSIVEUV1");
  76151. uv1 = true;
  76152. }
  76153. }
  76154. if (uv1) {
  76155. attribs.push(BABYLON.VertexBuffer.UVKind);
  76156. defines.push("#define UV1");
  76157. }
  76158. if (uv2) {
  76159. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  76160. defines.push("#define UV2");
  76161. }
  76162. // Bones
  76163. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  76164. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  76165. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  76166. if (mesh.numBoneInfluencers > 4) {
  76167. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  76168. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  76169. }
  76170. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  76171. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  76172. }
  76173. else {
  76174. defines.push("#define NUM_BONE_INFLUENCERS 0");
  76175. }
  76176. // Instances
  76177. if (useInstances) {
  76178. defines.push("#define INSTANCES");
  76179. attribs.push("world0");
  76180. attribs.push("world1");
  76181. attribs.push("world2");
  76182. attribs.push("world3");
  76183. }
  76184. // Get correct effect
  76185. var join = defines.join("\n");
  76186. if (this._cachedDefines !== join) {
  76187. this._cachedDefines = join;
  76188. this._glowMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  76189. }
  76190. return this._glowMapGenerationEffect.isReady();
  76191. };
  76192. /**
  76193. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  76194. */
  76195. HighlightLayer.prototype.render = function () {
  76196. var currentEffect = this._glowMapMergeEffect;
  76197. // Check
  76198. if (!currentEffect.isReady() || !this._blurTexture.isReady())
  76199. return;
  76200. var engine = this._scene.getEngine();
  76201. this.onBeforeComposeObservable.notifyObservers(this);
  76202. // Render
  76203. engine.enableEffect(currentEffect);
  76204. engine.setState(false);
  76205. // Cache
  76206. var previousStencilBuffer = engine.getStencilBuffer();
  76207. var previousStencilFunction = engine.getStencilFunction();
  76208. var previousStencilMask = engine.getStencilMask();
  76209. var previousStencilOperationPass = engine.getStencilOperationPass();
  76210. var previousStencilOperationFail = engine.getStencilOperationFail();
  76211. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  76212. var previousAlphaMode = engine.getAlphaMode();
  76213. // Texture
  76214. currentEffect.setTexture("textureSampler", this._blurTexture);
  76215. // VBOs
  76216. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  76217. // Stencil operations
  76218. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  76219. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  76220. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  76221. // Draw order
  76222. engine.setAlphaMode(this._options.alphaBlendingMode);
  76223. engine.setStencilMask(0x00);
  76224. engine.setStencilBuffer(true);
  76225. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  76226. if (this.outerGlow) {
  76227. currentEffect.setFloat("offset", 0);
  76228. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  76229. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  76230. }
  76231. if (this.innerGlow) {
  76232. currentEffect.setFloat("offset", 1);
  76233. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  76234. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  76235. }
  76236. // Restore Cache
  76237. engine.setStencilFunction(previousStencilFunction);
  76238. engine.setStencilMask(previousStencilMask);
  76239. engine.setAlphaMode(previousAlphaMode);
  76240. engine.setStencilBuffer(previousStencilBuffer);
  76241. engine.setStencilOperationPass(previousStencilOperationPass);
  76242. engine.setStencilOperationFail(previousStencilOperationFail);
  76243. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  76244. engine._stencilState.reset();
  76245. this.onAfterComposeObservable.notifyObservers(this);
  76246. // Handle size changes.
  76247. var size = this._mainTexture.getSize();
  76248. this.setMainTextureSize();
  76249. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  76250. // Recreate RTT and post processes on size change.
  76251. this.onSizeChangedObservable.notifyObservers(this);
  76252. this.disposeTextureAndPostProcesses();
  76253. this.createTextureAndPostProcesses();
  76254. }
  76255. };
  76256. /**
  76257. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  76258. * @param mesh The mesh to exclude from the highlight layer
  76259. */
  76260. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  76261. if (!this._excludedMeshes) {
  76262. return;
  76263. }
  76264. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  76265. if (!meshExcluded) {
  76266. this._excludedMeshes[mesh.uniqueId] = {
  76267. mesh: mesh,
  76268. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  76269. mesh.getEngine().setStencilBuffer(false);
  76270. }),
  76271. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  76272. mesh.getEngine().setStencilBuffer(true);
  76273. }),
  76274. };
  76275. }
  76276. };
  76277. /**
  76278. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  76279. * @param mesh The mesh to highlight
  76280. */
  76281. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  76282. if (!this._excludedMeshes) {
  76283. return;
  76284. }
  76285. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  76286. if (meshExcluded) {
  76287. if (meshExcluded.beforeRender) {
  76288. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  76289. }
  76290. if (meshExcluded.afterRender) {
  76291. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  76292. }
  76293. }
  76294. this._excludedMeshes[mesh.uniqueId] = null;
  76295. };
  76296. /**
  76297. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  76298. * @param mesh The mesh to highlight
  76299. * @param color The color of the highlight
  76300. * @param glowEmissiveOnly Extract the glow from the emissive texture
  76301. */
  76302. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  76303. var _this = this;
  76304. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  76305. if (!this._meshes) {
  76306. return;
  76307. }
  76308. var meshHighlight = this._meshes[mesh.uniqueId];
  76309. if (meshHighlight) {
  76310. meshHighlight.color = color;
  76311. }
  76312. else {
  76313. this._meshes[mesh.uniqueId] = {
  76314. mesh: mesh,
  76315. color: color,
  76316. // Lambda required for capture due to Observable this context
  76317. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  76318. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  76319. _this.defaultStencilReference(mesh);
  76320. }
  76321. else {
  76322. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  76323. }
  76324. }),
  76325. observerDefault: mesh.onAfterRenderObservable.add(this.defaultStencilReference),
  76326. glowEmissiveOnly: glowEmissiveOnly
  76327. };
  76328. }
  76329. this._shouldRender = true;
  76330. };
  76331. /**
  76332. * Remove a mesh from the highlight layer in order to make it stop glowing.
  76333. * @param mesh The mesh to highlight
  76334. */
  76335. HighlightLayer.prototype.removeMesh = function (mesh) {
  76336. if (!this._meshes) {
  76337. return;
  76338. }
  76339. var meshHighlight = this._meshes[mesh.uniqueId];
  76340. if (meshHighlight) {
  76341. if (meshHighlight.observerHighlight) {
  76342. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  76343. }
  76344. if (meshHighlight.observerDefault) {
  76345. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  76346. }
  76347. delete this._meshes[mesh.uniqueId];
  76348. }
  76349. this._shouldRender = false;
  76350. for (var meshHighlightToCheck in this._meshes) {
  76351. if (this._meshes[meshHighlightToCheck]) {
  76352. this._shouldRender = true;
  76353. break;
  76354. }
  76355. }
  76356. };
  76357. /**
  76358. * Returns true if the layer contains information to display, otherwise false.
  76359. */
  76360. HighlightLayer.prototype.shouldRender = function () {
  76361. return this.isEnabled && this._shouldRender;
  76362. };
  76363. /**
  76364. * Sets the main texture desired size which is the closest power of two
  76365. * of the engine canvas size.
  76366. */
  76367. HighlightLayer.prototype.setMainTextureSize = function () {
  76368. if (this._options.mainTextureFixedSize) {
  76369. this._mainTextureDesiredSize.width = this._options.mainTextureFixedSize;
  76370. this._mainTextureDesiredSize.height = this._options.mainTextureFixedSize;
  76371. }
  76372. else {
  76373. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._options.mainTextureRatio;
  76374. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._options.mainTextureRatio;
  76375. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  76376. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  76377. }
  76378. };
  76379. /**
  76380. * Force the stencil to the normal expected value for none glowing parts
  76381. */
  76382. HighlightLayer.prototype.defaultStencilReference = function (mesh) {
  76383. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.normalMeshStencilReference);
  76384. };
  76385. /**
  76386. * Dispose only the render target textures and post process.
  76387. */
  76388. HighlightLayer.prototype.disposeTextureAndPostProcesses = function () {
  76389. this._blurTexture.dispose();
  76390. this._mainTexture.dispose();
  76391. this._downSamplePostprocess.dispose();
  76392. this._horizontalBlurPostprocess.dispose();
  76393. this._verticalBlurPostprocess.dispose();
  76394. };
  76395. /**
  76396. * Dispose the highlight layer and free resources.
  76397. */
  76398. HighlightLayer.prototype.dispose = function () {
  76399. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  76400. if (vertexBuffer) {
  76401. vertexBuffer.dispose();
  76402. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  76403. }
  76404. if (this._indexBuffer) {
  76405. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  76406. this._indexBuffer = null;
  76407. }
  76408. // Clean textures and post processes
  76409. this.disposeTextureAndPostProcesses();
  76410. if (this._meshes) {
  76411. // Clean mesh references
  76412. for (var id in this._meshes) {
  76413. var meshHighlight = this._meshes[id];
  76414. if (meshHighlight && meshHighlight.mesh) {
  76415. if (meshHighlight.observerHighlight) {
  76416. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  76417. }
  76418. if (meshHighlight.observerDefault) {
  76419. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  76420. }
  76421. }
  76422. }
  76423. this._meshes = null;
  76424. }
  76425. if (this._excludedMeshes) {
  76426. for (var id in this._excludedMeshes) {
  76427. var meshHighlight = this._excludedMeshes[id];
  76428. if (meshHighlight) {
  76429. if (meshHighlight.beforeRender) {
  76430. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  76431. }
  76432. if (meshHighlight.afterRender) {
  76433. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  76434. }
  76435. }
  76436. }
  76437. this._excludedMeshes = null;
  76438. }
  76439. // Remove from scene
  76440. var index = this._scene.highlightLayers.indexOf(this, 0);
  76441. if (index > -1) {
  76442. this._scene.highlightLayers.splice(index, 1);
  76443. }
  76444. // Callback
  76445. this.onDisposeObservable.notifyObservers(this);
  76446. this.onDisposeObservable.clear();
  76447. this.onBeforeRenderMainTextureObservable.clear();
  76448. this.onBeforeBlurObservable.clear();
  76449. this.onBeforeComposeObservable.clear();
  76450. this.onAfterComposeObservable.clear();
  76451. this.onSizeChangedObservable.clear();
  76452. };
  76453. /**
  76454. * The neutral color used during the preparation of the glow effect.
  76455. * This is black by default as the blend operation is a blend operation.
  76456. */
  76457. HighlightLayer.neutralColor = new BABYLON.Color4(0, 0, 0, 0);
  76458. /**
  76459. * Stencil value used for glowing meshes.
  76460. */
  76461. HighlightLayer.glowingMeshStencilReference = 0x02;
  76462. /**
  76463. * Stencil value used for the other meshes in the scene.
  76464. */
  76465. HighlightLayer.normalMeshStencilReference = 0x01;
  76466. return HighlightLayer;
  76467. }());
  76468. BABYLON.HighlightLayer = HighlightLayer;
  76469. })(BABYLON || (BABYLON = {}));
  76470. //# sourceMappingURL=babylon.highlightlayer.js.map
  76471. var BABYLON;
  76472. (function (BABYLON) {
  76473. var AssetTaskState;
  76474. (function (AssetTaskState) {
  76475. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  76476. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  76477. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  76478. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  76479. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  76480. var AbstractAssetTask = /** @class */ (function () {
  76481. function AbstractAssetTask(name) {
  76482. this.name = name;
  76483. this.isCompleted = false;
  76484. this.taskState = AssetTaskState.INIT;
  76485. }
  76486. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  76487. var _this = this;
  76488. this.taskState = AssetTaskState.RUNNING;
  76489. this.runTask(scene, function () {
  76490. _this.onDoneCallback(onSuccess, onError);
  76491. }, function (msg, exception) {
  76492. _this.onErrorCallback(onError, msg, exception);
  76493. });
  76494. };
  76495. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  76496. throw new Error("runTask is not implemented");
  76497. };
  76498. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  76499. this.taskState = AssetTaskState.ERROR;
  76500. this.errorObject = {
  76501. message: message,
  76502. exception: exception
  76503. };
  76504. if (this.onError) {
  76505. this.onError(this, message, exception);
  76506. }
  76507. onError();
  76508. };
  76509. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  76510. try {
  76511. this.taskState = AssetTaskState.DONE;
  76512. this.isCompleted = true;
  76513. if (this.onSuccess) {
  76514. this.onSuccess(this);
  76515. }
  76516. onSuccess();
  76517. }
  76518. catch (e) {
  76519. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  76520. }
  76521. };
  76522. return AbstractAssetTask;
  76523. }());
  76524. BABYLON.AbstractAssetTask = AbstractAssetTask;
  76525. var AssetsProgressEvent = /** @class */ (function () {
  76526. function AssetsProgressEvent(remainingCount, totalCount, task) {
  76527. this.remainingCount = remainingCount;
  76528. this.totalCount = totalCount;
  76529. this.task = task;
  76530. }
  76531. return AssetsProgressEvent;
  76532. }());
  76533. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  76534. var MeshAssetTask = /** @class */ (function (_super) {
  76535. __extends(MeshAssetTask, _super);
  76536. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  76537. var _this = _super.call(this, name) || this;
  76538. _this.name = name;
  76539. _this.meshesNames = meshesNames;
  76540. _this.rootUrl = rootUrl;
  76541. _this.sceneFilename = sceneFilename;
  76542. return _this;
  76543. }
  76544. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  76545. var _this = this;
  76546. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  76547. _this.loadedMeshes = meshes;
  76548. _this.loadedParticleSystems = particleSystems;
  76549. _this.loadedSkeletons = skeletons;
  76550. onSuccess();
  76551. }, null, function (scene, message, exception) {
  76552. onError(message, exception);
  76553. });
  76554. };
  76555. return MeshAssetTask;
  76556. }(AbstractAssetTask));
  76557. BABYLON.MeshAssetTask = MeshAssetTask;
  76558. var TextFileAssetTask = /** @class */ (function (_super) {
  76559. __extends(TextFileAssetTask, _super);
  76560. function TextFileAssetTask(name, url) {
  76561. var _this = _super.call(this, name) || this;
  76562. _this.name = name;
  76563. _this.url = url;
  76564. return _this;
  76565. }
  76566. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  76567. var _this = this;
  76568. scene._loadFile(this.url, function (data) {
  76569. _this.text = data;
  76570. onSuccess();
  76571. }, undefined, false, true, function (request, exception) {
  76572. if (request) {
  76573. onError(request.status + " " + request.statusText, exception);
  76574. }
  76575. });
  76576. };
  76577. return TextFileAssetTask;
  76578. }(AbstractAssetTask));
  76579. BABYLON.TextFileAssetTask = TextFileAssetTask;
  76580. var BinaryFileAssetTask = /** @class */ (function (_super) {
  76581. __extends(BinaryFileAssetTask, _super);
  76582. function BinaryFileAssetTask(name, url) {
  76583. var _this = _super.call(this, name) || this;
  76584. _this.name = name;
  76585. _this.url = url;
  76586. return _this;
  76587. }
  76588. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  76589. var _this = this;
  76590. scene._loadFile(this.url, function (data) {
  76591. _this.data = data;
  76592. onSuccess();
  76593. }, undefined, true, true, function (request, exception) {
  76594. if (request) {
  76595. onError(request.status + " " + request.statusText, exception);
  76596. }
  76597. });
  76598. };
  76599. return BinaryFileAssetTask;
  76600. }(AbstractAssetTask));
  76601. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  76602. var ImageAssetTask = /** @class */ (function (_super) {
  76603. __extends(ImageAssetTask, _super);
  76604. function ImageAssetTask(name, url) {
  76605. var _this = _super.call(this, name) || this;
  76606. _this.name = name;
  76607. _this.url = url;
  76608. return _this;
  76609. }
  76610. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  76611. var _this = this;
  76612. var img = new Image();
  76613. BABYLON.Tools.SetCorsBehavior(this.url, img);
  76614. img.onload = function () {
  76615. _this.image = img;
  76616. onSuccess();
  76617. };
  76618. img.onerror = function (err) {
  76619. onError("Error loading image", err);
  76620. };
  76621. img.src = this.url;
  76622. };
  76623. return ImageAssetTask;
  76624. }(AbstractAssetTask));
  76625. BABYLON.ImageAssetTask = ImageAssetTask;
  76626. var TextureAssetTask = /** @class */ (function (_super) {
  76627. __extends(TextureAssetTask, _super);
  76628. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  76629. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  76630. var _this = _super.call(this, name) || this;
  76631. _this.name = name;
  76632. _this.url = url;
  76633. _this.noMipmap = noMipmap;
  76634. _this.invertY = invertY;
  76635. _this.samplingMode = samplingMode;
  76636. return _this;
  76637. }
  76638. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  76639. var onload = function () {
  76640. onSuccess();
  76641. };
  76642. var onerror = function (message, exception) {
  76643. onError(message, exception);
  76644. };
  76645. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  76646. };
  76647. return TextureAssetTask;
  76648. }(AbstractAssetTask));
  76649. BABYLON.TextureAssetTask = TextureAssetTask;
  76650. var CubeTextureAssetTask = /** @class */ (function (_super) {
  76651. __extends(CubeTextureAssetTask, _super);
  76652. function CubeTextureAssetTask(name, url, extensions, noMipmap, files) {
  76653. var _this = _super.call(this, name) || this;
  76654. _this.name = name;
  76655. _this.url = url;
  76656. _this.extensions = extensions;
  76657. _this.noMipmap = noMipmap;
  76658. _this.files = files;
  76659. return _this;
  76660. }
  76661. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  76662. var onload = function () {
  76663. onSuccess();
  76664. };
  76665. var onerror = function (message, exception) {
  76666. onError(message, exception);
  76667. };
  76668. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  76669. };
  76670. return CubeTextureAssetTask;
  76671. }(AbstractAssetTask));
  76672. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  76673. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  76674. __extends(HDRCubeTextureAssetTask, _super);
  76675. function HDRCubeTextureAssetTask(name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  76676. if (noMipmap === void 0) { noMipmap = false; }
  76677. if (generateHarmonics === void 0) { generateHarmonics = true; }
  76678. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  76679. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  76680. var _this = _super.call(this, name) || this;
  76681. _this.name = name;
  76682. _this.url = url;
  76683. _this.size = size;
  76684. _this.noMipmap = noMipmap;
  76685. _this.generateHarmonics = generateHarmonics;
  76686. _this.useInGammaSpace = useInGammaSpace;
  76687. _this.usePMREMGenerator = usePMREMGenerator;
  76688. return _this;
  76689. }
  76690. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  76691. var onload = function () {
  76692. onSuccess();
  76693. };
  76694. var onerror = function (message, exception) {
  76695. onError(message, exception);
  76696. };
  76697. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  76698. };
  76699. return HDRCubeTextureAssetTask;
  76700. }(AbstractAssetTask));
  76701. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  76702. var AssetsManager = /** @class */ (function () {
  76703. function AssetsManager(scene) {
  76704. this.tasks = new Array();
  76705. this.waitingTasksCount = 0;
  76706. //Observables
  76707. this.onTaskSuccessObservable = new BABYLON.Observable();
  76708. this.onTaskErrorObservable = new BABYLON.Observable();
  76709. this.onTasksDoneObservable = new BABYLON.Observable();
  76710. this.onProgressObservable = new BABYLON.Observable();
  76711. this.useDefaultLoadingScreen = true;
  76712. this._scene = scene;
  76713. }
  76714. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  76715. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  76716. this.tasks.push(task);
  76717. return task;
  76718. };
  76719. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  76720. var task = new TextFileAssetTask(taskName, url);
  76721. this.tasks.push(task);
  76722. return task;
  76723. };
  76724. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  76725. var task = new BinaryFileAssetTask(taskName, url);
  76726. this.tasks.push(task);
  76727. return task;
  76728. };
  76729. AssetsManager.prototype.addImageTask = function (taskName, url) {
  76730. var task = new ImageAssetTask(taskName, url);
  76731. this.tasks.push(task);
  76732. return task;
  76733. };
  76734. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  76735. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  76736. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  76737. this.tasks.push(task);
  76738. return task;
  76739. };
  76740. AssetsManager.prototype.addCubeTextureTask = function (name, url, extensions, noMipmap, files) {
  76741. var task = new CubeTextureAssetTask(name, url, extensions, noMipmap, files);
  76742. this.tasks.push(task);
  76743. return task;
  76744. };
  76745. AssetsManager.prototype.addHDRCubeTextureTask = function (name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  76746. if (noMipmap === void 0) { noMipmap = false; }
  76747. if (generateHarmonics === void 0) { generateHarmonics = true; }
  76748. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  76749. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  76750. var task = new HDRCubeTextureAssetTask(name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  76751. this.tasks.push(task);
  76752. return task;
  76753. };
  76754. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  76755. this.waitingTasksCount--;
  76756. try {
  76757. if (this.onProgress) {
  76758. this.onProgress(this.waitingTasksCount, this.tasks.length, task);
  76759. }
  76760. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this.waitingTasksCount, this.tasks.length, task));
  76761. }
  76762. catch (e) {
  76763. BABYLON.Tools.Error("Error running progress callbacks.");
  76764. console.log(e);
  76765. }
  76766. if (this.waitingTasksCount === 0) {
  76767. try {
  76768. if (this.onFinish) {
  76769. this.onFinish(this.tasks);
  76770. }
  76771. this.onTasksDoneObservable.notifyObservers(this.tasks);
  76772. }
  76773. catch (e) {
  76774. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  76775. console.log(e);
  76776. }
  76777. this._scene.getEngine().hideLoadingUI();
  76778. }
  76779. };
  76780. AssetsManager.prototype._runTask = function (task) {
  76781. var _this = this;
  76782. var done = function () {
  76783. try {
  76784. if (_this.onTaskSuccess) {
  76785. _this.onTaskSuccess(task);
  76786. }
  76787. _this.onTaskSuccessObservable.notifyObservers(task);
  76788. _this._decreaseWaitingTasksCount(task);
  76789. }
  76790. catch (e) {
  76791. error("Error executing task success callbacks", e);
  76792. }
  76793. };
  76794. var error = function (message, exception) {
  76795. task.errorObject = task.errorObject || {
  76796. message: message,
  76797. exception: exception
  76798. };
  76799. if (_this.onTaskError) {
  76800. _this.onTaskError(task);
  76801. }
  76802. _this.onTaskErrorObservable.notifyObservers(task);
  76803. _this._decreaseWaitingTasksCount(task);
  76804. };
  76805. task.run(this._scene, done, error);
  76806. };
  76807. AssetsManager.prototype.reset = function () {
  76808. this.tasks = new Array();
  76809. return this;
  76810. };
  76811. AssetsManager.prototype.load = function () {
  76812. this.waitingTasksCount = this.tasks.length;
  76813. if (this.waitingTasksCount === 0) {
  76814. if (this.onFinish) {
  76815. this.onFinish(this.tasks);
  76816. }
  76817. this.onTasksDoneObservable.notifyObservers(this.tasks);
  76818. return this;
  76819. }
  76820. if (this.useDefaultLoadingScreen) {
  76821. this._scene.getEngine().displayLoadingUI();
  76822. }
  76823. for (var index = 0; index < this.tasks.length; index++) {
  76824. var task = this.tasks[index];
  76825. this._runTask(task);
  76826. }
  76827. return this;
  76828. };
  76829. return AssetsManager;
  76830. }());
  76831. BABYLON.AssetsManager = AssetsManager;
  76832. })(BABYLON || (BABYLON = {}));
  76833. //# sourceMappingURL=babylon.assetsManager.js.map
  76834. var BABYLON;
  76835. (function (BABYLON) {
  76836. var serializedGeometries = [];
  76837. var serializeGeometry = function (geometry, serializationGeometries) {
  76838. if (serializedGeometries[geometry.id]) {
  76839. return;
  76840. }
  76841. if (geometry.doNotSerialize) {
  76842. return;
  76843. }
  76844. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  76845. serializationGeometries.boxes.push(geometry.serialize());
  76846. }
  76847. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  76848. serializationGeometries.spheres.push(geometry.serialize());
  76849. }
  76850. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  76851. serializationGeometries.cylinders.push(geometry.serialize());
  76852. }
  76853. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  76854. serializationGeometries.toruses.push(geometry.serialize());
  76855. }
  76856. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  76857. serializationGeometries.grounds.push(geometry.serialize());
  76858. }
  76859. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  76860. serializationGeometries.planes.push(geometry.serialize());
  76861. }
  76862. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  76863. serializationGeometries.torusKnots.push(geometry.serialize());
  76864. }
  76865. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  76866. throw new Error("Unknown primitive type");
  76867. }
  76868. else {
  76869. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  76870. }
  76871. serializedGeometries[geometry.id] = true;
  76872. };
  76873. var serializeMesh = function (mesh, serializationScene) {
  76874. var serializationObject = {};
  76875. // Geometry
  76876. var geometry = mesh._geometry;
  76877. if (geometry) {
  76878. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  76879. // 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
  76880. serializeGeometry(geometry, serializationScene.geometries);
  76881. }
  76882. }
  76883. // Custom
  76884. if (mesh.serialize) {
  76885. mesh.serialize(serializationObject);
  76886. }
  76887. return serializationObject;
  76888. };
  76889. var finalizeSingleMesh = function (mesh, serializationObject) {
  76890. //only works if the mesh is already loaded
  76891. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  76892. //serialize material
  76893. if (mesh.material) {
  76894. if (mesh.material instanceof BABYLON.StandardMaterial) {
  76895. serializationObject.materials = serializationObject.materials || [];
  76896. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  76897. serializationObject.materials.push(mesh.material.serialize());
  76898. }
  76899. }
  76900. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  76901. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  76902. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  76903. serializationObject.multiMaterials.push(mesh.material.serialize());
  76904. }
  76905. }
  76906. }
  76907. //serialize geometry
  76908. var geometry = mesh._geometry;
  76909. if (geometry) {
  76910. if (!serializationObject.geometries) {
  76911. serializationObject.geometries = {};
  76912. serializationObject.geometries.boxes = [];
  76913. serializationObject.geometries.spheres = [];
  76914. serializationObject.geometries.cylinders = [];
  76915. serializationObject.geometries.toruses = [];
  76916. serializationObject.geometries.grounds = [];
  76917. serializationObject.geometries.planes = [];
  76918. serializationObject.geometries.torusKnots = [];
  76919. serializationObject.geometries.vertexData = [];
  76920. }
  76921. serializeGeometry(geometry, serializationObject.geometries);
  76922. }
  76923. // Skeletons
  76924. if (mesh.skeleton) {
  76925. serializationObject.skeletons = serializationObject.skeletons || [];
  76926. serializationObject.skeletons.push(mesh.skeleton.serialize());
  76927. }
  76928. //serialize the actual mesh
  76929. serializationObject.meshes = serializationObject.meshes || [];
  76930. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  76931. }
  76932. };
  76933. var SceneSerializer = /** @class */ (function () {
  76934. function SceneSerializer() {
  76935. }
  76936. SceneSerializer.ClearCache = function () {
  76937. serializedGeometries = [];
  76938. };
  76939. SceneSerializer.Serialize = function (scene) {
  76940. var serializationObject = {};
  76941. SceneSerializer.ClearCache();
  76942. // Scene
  76943. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  76944. serializationObject.autoClear = scene.autoClear;
  76945. serializationObject.clearColor = scene.clearColor.asArray();
  76946. serializationObject.ambientColor = scene.ambientColor.asArray();
  76947. serializationObject.gravity = scene.gravity.asArray();
  76948. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  76949. serializationObject.workerCollisions = scene.workerCollisions;
  76950. // Fog
  76951. if (scene.fogMode && scene.fogMode !== 0) {
  76952. serializationObject.fogMode = scene.fogMode;
  76953. serializationObject.fogColor = scene.fogColor.asArray();
  76954. serializationObject.fogStart = scene.fogStart;
  76955. serializationObject.fogEnd = scene.fogEnd;
  76956. serializationObject.fogDensity = scene.fogDensity;
  76957. }
  76958. //Physics
  76959. if (scene.isPhysicsEnabled()) {
  76960. var physicEngine = scene.getPhysicsEngine();
  76961. if (physicEngine) {
  76962. serializationObject.physicsEnabled = true;
  76963. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  76964. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  76965. }
  76966. }
  76967. // Metadata
  76968. if (scene.metadata) {
  76969. serializationObject.metadata = scene.metadata;
  76970. }
  76971. // Morph targets
  76972. serializationObject.morphTargetManagers = [];
  76973. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  76974. var abstractMesh = _a[_i];
  76975. var manager = abstractMesh.morphTargetManager;
  76976. if (manager) {
  76977. serializationObject.morphTargetManagers.push(manager.serialize());
  76978. }
  76979. }
  76980. // Lights
  76981. serializationObject.lights = [];
  76982. var index;
  76983. var light;
  76984. for (index = 0; index < scene.lights.length; index++) {
  76985. light = scene.lights[index];
  76986. if (!light.doNotSerialize) {
  76987. serializationObject.lights.push(light.serialize());
  76988. }
  76989. }
  76990. // Cameras
  76991. serializationObject.cameras = [];
  76992. for (index = 0; index < scene.cameras.length; index++) {
  76993. var camera = scene.cameras[index];
  76994. if (!camera.doNotSerialize) {
  76995. serializationObject.cameras.push(camera.serialize());
  76996. }
  76997. }
  76998. if (scene.activeCamera) {
  76999. serializationObject.activeCameraID = scene.activeCamera.id;
  77000. }
  77001. // Animations
  77002. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  77003. // Materials
  77004. serializationObject.materials = [];
  77005. serializationObject.multiMaterials = [];
  77006. var material;
  77007. for (index = 0; index < scene.materials.length; index++) {
  77008. material = scene.materials[index];
  77009. if (!material.doNotSerialize) {
  77010. serializationObject.materials.push(material.serialize());
  77011. }
  77012. }
  77013. // MultiMaterials
  77014. serializationObject.multiMaterials = [];
  77015. for (index = 0; index < scene.multiMaterials.length; index++) {
  77016. var multiMaterial = scene.multiMaterials[index];
  77017. serializationObject.multiMaterials.push(multiMaterial.serialize());
  77018. }
  77019. // Skeletons
  77020. serializationObject.skeletons = [];
  77021. for (index = 0; index < scene.skeletons.length; index++) {
  77022. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  77023. }
  77024. // Transform nodes
  77025. serializationObject.transformNodes = [];
  77026. for (index = 0; index < scene.transformNodes.length; index++) {
  77027. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  77028. }
  77029. // Geometries
  77030. serializationObject.geometries = {};
  77031. serializationObject.geometries.boxes = [];
  77032. serializationObject.geometries.spheres = [];
  77033. serializationObject.geometries.cylinders = [];
  77034. serializationObject.geometries.toruses = [];
  77035. serializationObject.geometries.grounds = [];
  77036. serializationObject.geometries.planes = [];
  77037. serializationObject.geometries.torusKnots = [];
  77038. serializationObject.geometries.vertexData = [];
  77039. serializedGeometries = [];
  77040. var geometries = scene.getGeometries();
  77041. for (index = 0; index < geometries.length; index++) {
  77042. var geometry = geometries[index];
  77043. if (geometry.isReady()) {
  77044. serializeGeometry(geometry, serializationObject.geometries);
  77045. }
  77046. }
  77047. // Meshes
  77048. serializationObject.meshes = [];
  77049. for (index = 0; index < scene.meshes.length; index++) {
  77050. var abstractMesh = scene.meshes[index];
  77051. if (abstractMesh instanceof BABYLON.Mesh) {
  77052. var mesh = abstractMesh;
  77053. if (!mesh.doNotSerialize) {
  77054. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  77055. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  77056. }
  77057. }
  77058. }
  77059. }
  77060. // Particles Systems
  77061. serializationObject.particleSystems = [];
  77062. for (index = 0; index < scene.particleSystems.length; index++) {
  77063. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  77064. }
  77065. // Lens flares
  77066. serializationObject.lensFlareSystems = [];
  77067. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  77068. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  77069. }
  77070. // Shadows
  77071. serializationObject.shadowGenerators = [];
  77072. for (index = 0; index < scene.lights.length; index++) {
  77073. light = scene.lights[index];
  77074. var shadowGenerator = light.getShadowGenerator();
  77075. if (shadowGenerator) {
  77076. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  77077. }
  77078. }
  77079. // Action Manager
  77080. if (scene.actionManager) {
  77081. serializationObject.actions = scene.actionManager.serialize("scene");
  77082. }
  77083. // Audio
  77084. serializationObject.sounds = [];
  77085. for (index = 0; index < scene.soundTracks.length; index++) {
  77086. var soundtrack = scene.soundTracks[index];
  77087. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  77088. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  77089. }
  77090. }
  77091. return serializationObject;
  77092. };
  77093. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  77094. if (withParents === void 0) { withParents = false; }
  77095. if (withChildren === void 0) { withChildren = false; }
  77096. var serializationObject = {};
  77097. SceneSerializer.ClearCache();
  77098. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  77099. if (withParents || withChildren) {
  77100. //deliberate for loop! not for each, appended should be processed as well.
  77101. for (var i = 0; i < toSerialize.length; ++i) {
  77102. if (withChildren) {
  77103. toSerialize[i].getDescendants().forEach(function (node) {
  77104. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  77105. toSerialize.push(node);
  77106. }
  77107. });
  77108. }
  77109. //make sure the array doesn't contain the object already
  77110. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  77111. toSerialize.push(toSerialize[i].parent);
  77112. }
  77113. }
  77114. }
  77115. toSerialize.forEach(function (mesh) {
  77116. finalizeSingleMesh(mesh, serializationObject);
  77117. });
  77118. return serializationObject;
  77119. };
  77120. return SceneSerializer;
  77121. }());
  77122. BABYLON.SceneSerializer = SceneSerializer;
  77123. })(BABYLON || (BABYLON = {}));
  77124. //# sourceMappingURL=babylon.sceneSerializer.js.map
  77125. var BABYLON;
  77126. (function (BABYLON) {
  77127. var ReflectionProbe = /** @class */ (function () {
  77128. function ReflectionProbe(name, size, scene, generateMipMaps) {
  77129. if (generateMipMaps === void 0) { generateMipMaps = true; }
  77130. var _this = this;
  77131. this.name = name;
  77132. this._viewMatrix = BABYLON.Matrix.Identity();
  77133. this._target = BABYLON.Vector3.Zero();
  77134. this._add = BABYLON.Vector3.Zero();
  77135. this.invertYAxis = false;
  77136. this.position = BABYLON.Vector3.Zero();
  77137. this._scene = scene;
  77138. this._scene.reflectionProbes.push(this);
  77139. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  77140. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  77141. switch (faceIndex) {
  77142. case 0:
  77143. _this._add.copyFromFloats(1, 0, 0);
  77144. break;
  77145. case 1:
  77146. _this._add.copyFromFloats(-1, 0, 0);
  77147. break;
  77148. case 2:
  77149. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  77150. break;
  77151. case 3:
  77152. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  77153. break;
  77154. case 4:
  77155. _this._add.copyFromFloats(0, 0, 1);
  77156. break;
  77157. case 5:
  77158. _this._add.copyFromFloats(0, 0, -1);
  77159. break;
  77160. }
  77161. if (_this._attachedMesh) {
  77162. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  77163. }
  77164. _this.position.addToRef(_this._add, _this._target);
  77165. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  77166. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  77167. scene._forcedViewPosition = _this.position;
  77168. });
  77169. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  77170. scene._forcedViewPosition = null;
  77171. scene.updateTransformMatrix(true);
  77172. });
  77173. if (scene.activeCamera) {
  77174. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  77175. }
  77176. }
  77177. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  77178. get: function () {
  77179. return this._renderTargetTexture.samples;
  77180. },
  77181. set: function (value) {
  77182. this._renderTargetTexture.samples = value;
  77183. },
  77184. enumerable: true,
  77185. configurable: true
  77186. });
  77187. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  77188. get: function () {
  77189. return this._renderTargetTexture.refreshRate;
  77190. },
  77191. set: function (value) {
  77192. this._renderTargetTexture.refreshRate = value;
  77193. },
  77194. enumerable: true,
  77195. configurable: true
  77196. });
  77197. ReflectionProbe.prototype.getScene = function () {
  77198. return this._scene;
  77199. };
  77200. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  77201. get: function () {
  77202. return this._renderTargetTexture;
  77203. },
  77204. enumerable: true,
  77205. configurable: true
  77206. });
  77207. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  77208. get: function () {
  77209. return this._renderTargetTexture.renderList;
  77210. },
  77211. enumerable: true,
  77212. configurable: true
  77213. });
  77214. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  77215. this._attachedMesh = mesh;
  77216. };
  77217. /**
  77218. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  77219. *
  77220. * @param renderingGroupId The rendering group id corresponding to its index
  77221. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  77222. */
  77223. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  77224. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  77225. };
  77226. ReflectionProbe.prototype.dispose = function () {
  77227. var index = this._scene.reflectionProbes.indexOf(this);
  77228. if (index !== -1) {
  77229. // Remove from the scene if found
  77230. this._scene.reflectionProbes.splice(index, 1);
  77231. }
  77232. if (this._renderTargetTexture) {
  77233. this._renderTargetTexture.dispose();
  77234. this._renderTargetTexture = null;
  77235. }
  77236. };
  77237. return ReflectionProbe;
  77238. }());
  77239. BABYLON.ReflectionProbe = ReflectionProbe;
  77240. })(BABYLON || (BABYLON = {}));
  77241. //# sourceMappingURL=babylon.reflectionProbe.js.map
  77242. var BABYLON;
  77243. (function (BABYLON) {
  77244. var Layer = /** @class */ (function () {
  77245. function Layer(name, imgUrl, scene, isBackground, color) {
  77246. this.name = name;
  77247. this.scale = new BABYLON.Vector2(1, 1);
  77248. this.offset = new BABYLON.Vector2(0, 0);
  77249. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  77250. this.layerMask = 0x0FFFFFFF;
  77251. this._vertexBuffers = {};
  77252. // Events
  77253. /**
  77254. * An event triggered when the layer is disposed.
  77255. * @type {BABYLON.Observable}
  77256. */
  77257. this.onDisposeObservable = new BABYLON.Observable();
  77258. /**
  77259. * An event triggered before rendering the scene
  77260. * @type {BABYLON.Observable}
  77261. */
  77262. this.onBeforeRenderObservable = new BABYLON.Observable();
  77263. /**
  77264. * An event triggered after rendering the scene
  77265. * @type {BABYLON.Observable}
  77266. */
  77267. this.onAfterRenderObservable = new BABYLON.Observable();
  77268. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  77269. this.isBackground = isBackground === undefined ? true : isBackground;
  77270. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  77271. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  77272. this._scene.layers.push(this);
  77273. var engine = this._scene.getEngine();
  77274. // VBO
  77275. var vertices = [];
  77276. vertices.push(1, 1);
  77277. vertices.push(-1, 1);
  77278. vertices.push(-1, -1);
  77279. vertices.push(1, -1);
  77280. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  77281. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  77282. this._createIndexBuffer();
  77283. // Effects
  77284. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  77285. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  77286. }
  77287. Object.defineProperty(Layer.prototype, "onDispose", {
  77288. set: function (callback) {
  77289. if (this._onDisposeObserver) {
  77290. this.onDisposeObservable.remove(this._onDisposeObserver);
  77291. }
  77292. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  77293. },
  77294. enumerable: true,
  77295. configurable: true
  77296. });
  77297. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  77298. set: function (callback) {
  77299. if (this._onBeforeRenderObserver) {
  77300. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  77301. }
  77302. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  77303. },
  77304. enumerable: true,
  77305. configurable: true
  77306. });
  77307. Object.defineProperty(Layer.prototype, "onAfterRender", {
  77308. set: function (callback) {
  77309. if (this._onAfterRenderObserver) {
  77310. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  77311. }
  77312. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  77313. },
  77314. enumerable: true,
  77315. configurable: true
  77316. });
  77317. Layer.prototype._createIndexBuffer = function () {
  77318. var engine = this._scene.getEngine();
  77319. // Indices
  77320. var indices = [];
  77321. indices.push(0);
  77322. indices.push(1);
  77323. indices.push(2);
  77324. indices.push(0);
  77325. indices.push(2);
  77326. indices.push(3);
  77327. this._indexBuffer = engine.createIndexBuffer(indices);
  77328. };
  77329. Layer.prototype._rebuild = function () {
  77330. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  77331. if (vb) {
  77332. vb._rebuild();
  77333. }
  77334. this._createIndexBuffer();
  77335. };
  77336. Layer.prototype.render = function () {
  77337. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  77338. // Check
  77339. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  77340. return;
  77341. var engine = this._scene.getEngine();
  77342. this.onBeforeRenderObservable.notifyObservers(this);
  77343. // Render
  77344. engine.enableEffect(currentEffect);
  77345. engine.setState(false);
  77346. // Texture
  77347. currentEffect.setTexture("textureSampler", this.texture);
  77348. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  77349. // Color
  77350. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  77351. // Scale / offset
  77352. currentEffect.setVector2("offset", this.offset);
  77353. currentEffect.setVector2("scale", this.scale);
  77354. // VBOs
  77355. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  77356. // Draw order
  77357. if (!this.alphaTest) {
  77358. engine.setAlphaMode(this.alphaBlendingMode);
  77359. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  77360. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  77361. }
  77362. else {
  77363. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  77364. }
  77365. this.onAfterRenderObservable.notifyObservers(this);
  77366. };
  77367. Layer.prototype.dispose = function () {
  77368. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  77369. if (vertexBuffer) {
  77370. vertexBuffer.dispose();
  77371. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  77372. }
  77373. if (this._indexBuffer) {
  77374. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  77375. this._indexBuffer = null;
  77376. }
  77377. if (this.texture) {
  77378. this.texture.dispose();
  77379. this.texture = null;
  77380. }
  77381. // Remove from scene
  77382. var index = this._scene.layers.indexOf(this);
  77383. this._scene.layers.splice(index, 1);
  77384. // Callback
  77385. this.onDisposeObservable.notifyObservers(this);
  77386. this.onDisposeObservable.clear();
  77387. this.onAfterRenderObservable.clear();
  77388. this.onBeforeRenderObservable.clear();
  77389. };
  77390. return Layer;
  77391. }());
  77392. BABYLON.Layer = Layer;
  77393. })(BABYLON || (BABYLON = {}));
  77394. //# sourceMappingURL=babylon.layer.js.map
  77395. var BABYLON;
  77396. (function (BABYLON) {
  77397. var TextureTools = /** @class */ (function () {
  77398. function TextureTools() {
  77399. }
  77400. /**
  77401. * Uses the GPU to create a copy texture rescaled at a given size
  77402. * @param texture Texture to copy from
  77403. * @param width Desired width
  77404. * @param height Desired height
  77405. * @return Generated texture
  77406. */
  77407. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  77408. if (useBilinearMode === void 0) { useBilinearMode = true; }
  77409. var scene = texture.getScene();
  77410. var engine = scene.getEngine();
  77411. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  77412. rtt.wrapU = texture.wrapU;
  77413. rtt.wrapV = texture.wrapV;
  77414. rtt.uOffset = texture.uOffset;
  77415. rtt.vOffset = texture.vOffset;
  77416. rtt.uScale = texture.uScale;
  77417. rtt.vScale = texture.vScale;
  77418. rtt.uAng = texture.uAng;
  77419. rtt.vAng = texture.vAng;
  77420. rtt.wAng = texture.wAng;
  77421. rtt.coordinatesIndex = texture.coordinatesIndex;
  77422. rtt.level = texture.level;
  77423. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  77424. rtt._texture.isReady = false;
  77425. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77426. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77427. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  77428. passPostProcess.getEffect().executeWhenCompiled(function () {
  77429. passPostProcess.onApply = function (effect) {
  77430. effect.setTexture("textureSampler", texture);
  77431. };
  77432. var internalTexture = rtt.getInternalTexture();
  77433. if (internalTexture) {
  77434. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  77435. engine.unBindFramebuffer(internalTexture);
  77436. rtt.disposeFramebufferObjects();
  77437. passPostProcess.dispose();
  77438. internalTexture.isReady = true;
  77439. }
  77440. });
  77441. return rtt;
  77442. };
  77443. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  77444. if (!scene._environmentBRDFTexture) {
  77445. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  77446. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77447. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77448. scene._environmentBRDFTexture = texture;
  77449. }
  77450. return scene._environmentBRDFTexture;
  77451. };
  77452. 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=";
  77453. return TextureTools;
  77454. }());
  77455. BABYLON.TextureTools = TextureTools;
  77456. })(BABYLON || (BABYLON = {}));
  77457. //# sourceMappingURL=babylon.textureTools.js.map
  77458. var BABYLON;
  77459. (function (BABYLON) {
  77460. var FramingBehavior = /** @class */ (function () {
  77461. function FramingBehavior() {
  77462. this._mode = FramingBehavior.FitFrustumSidesMode;
  77463. this._radiusScale = 1.0;
  77464. this._positionScale = 0.5;
  77465. this._defaultElevation = 0.3;
  77466. this._elevationReturnTime = 1500;
  77467. this._elevationReturnWaitTime = 1000;
  77468. this._zoomStopsAnimation = false;
  77469. this._framingTime = 1500;
  77470. this._isPointerDown = false;
  77471. this._lastInteractionTime = -Infinity;
  77472. // Framing control
  77473. this._animatables = new Array();
  77474. this._betaIsAnimating = false;
  77475. }
  77476. Object.defineProperty(FramingBehavior.prototype, "name", {
  77477. get: function () {
  77478. return "Framing";
  77479. },
  77480. enumerable: true,
  77481. configurable: true
  77482. });
  77483. Object.defineProperty(FramingBehavior.prototype, "mode", {
  77484. /**
  77485. * Gets current mode used by the behavior.
  77486. */
  77487. get: function () {
  77488. return this._mode;
  77489. },
  77490. /**
  77491. * Sets the current mode used by the behavior
  77492. */
  77493. set: function (mode) {
  77494. this._mode = mode;
  77495. },
  77496. enumerable: true,
  77497. configurable: true
  77498. });
  77499. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  77500. /**
  77501. * Gets the scale applied to the radius
  77502. */
  77503. get: function () {
  77504. return this._radiusScale;
  77505. },
  77506. /**
  77507. * Sets the scale applied to the radius (1 by default)
  77508. */
  77509. set: function (radius) {
  77510. this._radiusScale = radius;
  77511. },
  77512. enumerable: true,
  77513. configurable: true
  77514. });
  77515. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  77516. /**
  77517. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  77518. */
  77519. get: function () {
  77520. return this._positionScale;
  77521. },
  77522. /**
  77523. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  77524. */
  77525. set: function (scale) {
  77526. this._positionScale = scale;
  77527. },
  77528. enumerable: true,
  77529. configurable: true
  77530. });
  77531. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  77532. /**
  77533. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  77534. * behaviour is triggered, in radians.
  77535. */
  77536. get: function () {
  77537. return this._defaultElevation;
  77538. },
  77539. /**
  77540. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  77541. * behaviour is triggered, in radians.
  77542. */
  77543. set: function (elevation) {
  77544. this._defaultElevation = elevation;
  77545. },
  77546. enumerable: true,
  77547. configurable: true
  77548. });
  77549. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  77550. /**
  77551. * Gets the time (in milliseconds) taken to return to the default beta position.
  77552. * Negative value indicates camera should not return to default.
  77553. */
  77554. get: function () {
  77555. return this._elevationReturnTime;
  77556. },
  77557. /**
  77558. * Sets the time (in milliseconds) taken to return to the default beta position.
  77559. * Negative value indicates camera should not return to default.
  77560. */
  77561. set: function (speed) {
  77562. this._elevationReturnTime = speed;
  77563. },
  77564. enumerable: true,
  77565. configurable: true
  77566. });
  77567. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  77568. /**
  77569. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  77570. */
  77571. get: function () {
  77572. return this._elevationReturnWaitTime;
  77573. },
  77574. /**
  77575. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  77576. */
  77577. set: function (time) {
  77578. this._elevationReturnWaitTime = time;
  77579. },
  77580. enumerable: true,
  77581. configurable: true
  77582. });
  77583. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  77584. /**
  77585. * Gets the flag that indicates if user zooming should stop animation.
  77586. */
  77587. get: function () {
  77588. return this._zoomStopsAnimation;
  77589. },
  77590. /**
  77591. * Sets the flag that indicates if user zooming should stop animation.
  77592. */
  77593. set: function (flag) {
  77594. this._zoomStopsAnimation = flag;
  77595. },
  77596. enumerable: true,
  77597. configurable: true
  77598. });
  77599. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  77600. /**
  77601. * Gets the transition time when framing the mesh, in milliseconds
  77602. */
  77603. get: function () {
  77604. return this._framingTime;
  77605. },
  77606. /**
  77607. * Sets the transition time when framing the mesh, in milliseconds
  77608. */
  77609. set: function (time) {
  77610. this._framingTime = time;
  77611. },
  77612. enumerable: true,
  77613. configurable: true
  77614. });
  77615. FramingBehavior.prototype.init = function () {
  77616. // Do notihng
  77617. };
  77618. FramingBehavior.prototype.attach = function (camera) {
  77619. var _this = this;
  77620. this._attachedCamera = camera;
  77621. var scene = this._attachedCamera.getScene();
  77622. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  77623. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  77624. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  77625. _this._isPointerDown = true;
  77626. return;
  77627. }
  77628. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  77629. _this._isPointerDown = false;
  77630. }
  77631. });
  77632. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  77633. if (mesh) {
  77634. _this.zoomOnMesh(mesh);
  77635. }
  77636. });
  77637. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  77638. // Stop the animation if there is user interaction and the animation should stop for this interaction
  77639. _this._applyUserInteraction();
  77640. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  77641. // back to the default position after a given timeout
  77642. _this._maintainCameraAboveGround();
  77643. });
  77644. };
  77645. FramingBehavior.prototype.detach = function () {
  77646. if (!this._attachedCamera) {
  77647. return;
  77648. }
  77649. var scene = this._attachedCamera.getScene();
  77650. if (this._onPrePointerObservableObserver) {
  77651. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  77652. }
  77653. if (this._onAfterCheckInputsObserver) {
  77654. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  77655. }
  77656. if (this._onMeshTargetChangedObserver) {
  77657. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  77658. }
  77659. this._attachedCamera = null;
  77660. };
  77661. /**
  77662. * Targets the given mesh and updates zoom level accordingly.
  77663. * @param mesh The mesh to target.
  77664. * @param radius Optional. If a cached radius position already exists, overrides default.
  77665. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  77666. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  77667. * @param onAnimationEnd Callback triggered at the end of the framing animation
  77668. */
  77669. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  77670. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  77671. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  77672. mesh.computeWorldMatrix(true);
  77673. var boundingBox = mesh.getBoundingInfo().boundingBox;
  77674. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  77675. };
  77676. /**
  77677. * Targets the given mesh with its children and updates zoom level accordingly.
  77678. * @param mesh The mesh to target.
  77679. * @param radius Optional. If a cached radius position already exists, overrides default.
  77680. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  77681. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  77682. * @param onAnimationEnd Callback triggered at the end of the framing animation
  77683. */
  77684. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  77685. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  77686. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  77687. mesh.computeWorldMatrix(true);
  77688. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  77689. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  77690. };
  77691. /**
  77692. * Targets the given meshes with their children and updates zoom level accordingly.
  77693. * @param meshes The mesh to target.
  77694. * @param radius Optional. If a cached radius position already exists, overrides default.
  77695. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  77696. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  77697. * @param onAnimationEnd Callback triggered at the end of the framing animation
  77698. */
  77699. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  77700. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  77701. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  77702. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  77703. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  77704. for (var i = 0; i < meshes.length; i++) {
  77705. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  77706. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  77707. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  77708. }
  77709. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  77710. };
  77711. /**
  77712. * Targets the given mesh and updates zoom level accordingly.
  77713. * @param mesh The mesh to target.
  77714. * @param radius Optional. If a cached radius position already exists, overrides default.
  77715. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  77716. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  77717. * @param onAnimationEnd Callback triggered at the end of the framing animation
  77718. */
  77719. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  77720. var _this = this;
  77721. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  77722. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  77723. var zoomTarget;
  77724. if (!this._attachedCamera) {
  77725. return;
  77726. }
  77727. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  77728. var bottom = minimumWorld.y;
  77729. var top = maximumWorld.y;
  77730. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  77731. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  77732. if (focusOnOriginXZ) {
  77733. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  77734. }
  77735. else {
  77736. var centerWorld = minimumWorld.add(radiusWorld);
  77737. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  77738. }
  77739. if (!this._vectorTransition) {
  77740. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  77741. }
  77742. this._betaIsAnimating = true;
  77743. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  77744. if (animatable) {
  77745. this._animatables.push(animatable);
  77746. }
  77747. // sets the radius and lower radius bounds
  77748. // Small delta ensures camera is not always at lower zoom limit.
  77749. var radius = 0;
  77750. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  77751. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  77752. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  77753. radius = position;
  77754. }
  77755. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  77756. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  77757. if (this._attachedCamera.lowerRadiusLimit === null) {
  77758. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  77759. }
  77760. }
  77761. // Set sensibilities
  77762. var extend = maximumWorld.subtract(minimumWorld).length();
  77763. this._attachedCamera.panningSensibility = 5000 / extend;
  77764. this._attachedCamera.wheelPrecision = 100 / radius;
  77765. // transition to new radius
  77766. if (!this._radiusTransition) {
  77767. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  77768. }
  77769. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  77770. if (onAnimationEnd) {
  77771. onAnimationEnd();
  77772. }
  77773. if (_this._attachedCamera) {
  77774. _this._attachedCamera.storeState();
  77775. }
  77776. });
  77777. if (animatable) {
  77778. this._animatables.push(animatable);
  77779. }
  77780. };
  77781. /**
  77782. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  77783. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  77784. * frustum width.
  77785. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  77786. * to fully enclose the mesh in the viewing frustum.
  77787. */
  77788. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  77789. var size = maximumWorld.subtract(minimumWorld);
  77790. var boxVectorGlobalDiagonal = size.length();
  77791. var frustumSlope = this._getFrustumSlope();
  77792. // Formula for setting distance
  77793. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  77794. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  77795. // Horizon distance
  77796. var radius = radiusWithoutFraming * this._radiusScale;
  77797. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  77798. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  77799. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  77800. var camera = this._attachedCamera;
  77801. if (!camera) {
  77802. return 0;
  77803. }
  77804. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  77805. // Don't exceed the requested limit
  77806. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  77807. }
  77808. // Don't exceed the upper radius limit
  77809. if (camera.upperRadiusLimit) {
  77810. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  77811. }
  77812. return distance;
  77813. };
  77814. /**
  77815. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  77816. * is automatically returned to its default position (expected to be above ground plane).
  77817. */
  77818. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  77819. var _this = this;
  77820. if (this._elevationReturnTime < 0) {
  77821. return;
  77822. }
  77823. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  77824. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  77825. var limitBeta = Math.PI * 0.5;
  77826. // Bring the camera back up if below the ground plane
  77827. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  77828. this._betaIsAnimating = true;
  77829. //Transition to new position
  77830. this.stopAllAnimations();
  77831. if (!this._betaTransition) {
  77832. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  77833. }
  77834. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  77835. _this._clearAnimationLocks();
  77836. _this.stopAllAnimations();
  77837. });
  77838. if (animatabe) {
  77839. this._animatables.push(animatabe);
  77840. }
  77841. }
  77842. };
  77843. /**
  77844. * Returns the frustum slope based on the canvas ratio and camera FOV
  77845. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  77846. */
  77847. FramingBehavior.prototype._getFrustumSlope = function () {
  77848. // Calculate the viewport ratio
  77849. // Aspect Ratio is Height/Width.
  77850. var camera = this._attachedCamera;
  77851. if (!camera) {
  77852. return BABYLON.Vector2.Zero();
  77853. }
  77854. var engine = camera.getScene().getEngine();
  77855. var aspectRatio = engine.getAspectRatio(camera);
  77856. // Camera FOV is the vertical field of view (top-bottom) in radians.
  77857. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  77858. var frustumSlopeY = Math.tan(camera.fov / 2);
  77859. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  77860. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  77861. // along the forward vector.
  77862. var frustumSlopeX = frustumSlopeY * aspectRatio;
  77863. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  77864. };
  77865. /**
  77866. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  77867. */
  77868. FramingBehavior.prototype._clearAnimationLocks = function () {
  77869. this._betaIsAnimating = false;
  77870. };
  77871. /**
  77872. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  77873. */
  77874. FramingBehavior.prototype._applyUserInteraction = function () {
  77875. if (this.isUserIsMoving) {
  77876. this._lastInteractionTime = BABYLON.Tools.Now;
  77877. this.stopAllAnimations();
  77878. this._clearAnimationLocks();
  77879. }
  77880. };
  77881. /**
  77882. * Stops and removes all animations that have been applied to the camera
  77883. */
  77884. FramingBehavior.prototype.stopAllAnimations = function () {
  77885. if (this._attachedCamera) {
  77886. this._attachedCamera.animations = [];
  77887. }
  77888. while (this._animatables.length) {
  77889. if (this._animatables[0]) {
  77890. this._animatables[0].onAnimationEnd = null;
  77891. this._animatables[0].stop();
  77892. }
  77893. this._animatables.shift();
  77894. }
  77895. };
  77896. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  77897. /**
  77898. * Gets a value indicating if the user is moving the camera
  77899. */
  77900. get: function () {
  77901. if (!this._attachedCamera) {
  77902. return false;
  77903. }
  77904. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  77905. this._attachedCamera.inertialBetaOffset !== 0 ||
  77906. this._attachedCamera.inertialRadiusOffset !== 0 ||
  77907. this._attachedCamera.inertialPanningX !== 0 ||
  77908. this._attachedCamera.inertialPanningY !== 0 ||
  77909. this._isPointerDown;
  77910. },
  77911. enumerable: true,
  77912. configurable: true
  77913. });
  77914. /**
  77915. * The easing function used by animations
  77916. */
  77917. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  77918. /**
  77919. * The easing mode used by animations
  77920. */
  77921. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  77922. // Statics
  77923. /**
  77924. * The camera can move all the way towards the mesh.
  77925. */
  77926. FramingBehavior.IgnoreBoundsSizeMode = 0;
  77927. /**
  77928. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  77929. */
  77930. FramingBehavior.FitFrustumSidesMode = 1;
  77931. return FramingBehavior;
  77932. }());
  77933. BABYLON.FramingBehavior = FramingBehavior;
  77934. })(BABYLON || (BABYLON = {}));
  77935. //# sourceMappingURL=babylon.framingBehavior.js.map
  77936. var BABYLON;
  77937. (function (BABYLON) {
  77938. /**
  77939. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  77940. */
  77941. var BouncingBehavior = /** @class */ (function () {
  77942. function BouncingBehavior() {
  77943. /**
  77944. * The duration of the animation, in milliseconds
  77945. */
  77946. this.transitionDuration = 450;
  77947. /**
  77948. * Length of the distance animated by the transition when lower radius is reached
  77949. */
  77950. this.lowerRadiusTransitionRange = 2;
  77951. /**
  77952. * Length of the distance animated by the transition when upper radius is reached
  77953. */
  77954. this.upperRadiusTransitionRange = -2;
  77955. this._autoTransitionRange = false;
  77956. // Animations
  77957. this._radiusIsAnimating = false;
  77958. this._radiusBounceTransition = null;
  77959. this._animatables = new Array();
  77960. }
  77961. Object.defineProperty(BouncingBehavior.prototype, "name", {
  77962. get: function () {
  77963. return "Bouncing";
  77964. },
  77965. enumerable: true,
  77966. configurable: true
  77967. });
  77968. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  77969. /**
  77970. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  77971. */
  77972. get: function () {
  77973. return this._autoTransitionRange;
  77974. },
  77975. /**
  77976. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  77977. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  77978. */
  77979. set: function (value) {
  77980. var _this = this;
  77981. if (this._autoTransitionRange === value) {
  77982. return;
  77983. }
  77984. this._autoTransitionRange = value;
  77985. var camera = this._attachedCamera;
  77986. if (!camera) {
  77987. return;
  77988. }
  77989. if (value) {
  77990. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  77991. if (!mesh) {
  77992. return;
  77993. }
  77994. mesh.computeWorldMatrix(true);
  77995. var diagonal = mesh.getBoundingInfo().diagonalLength;
  77996. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  77997. _this.upperRadiusTransitionRange = diagonal * 0.05;
  77998. });
  77999. }
  78000. else if (this._onMeshTargetChangedObserver) {
  78001. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  78002. }
  78003. },
  78004. enumerable: true,
  78005. configurable: true
  78006. });
  78007. BouncingBehavior.prototype.init = function () {
  78008. // Do notihng
  78009. };
  78010. BouncingBehavior.prototype.attach = function (camera) {
  78011. var _this = this;
  78012. this._attachedCamera = camera;
  78013. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  78014. if (!_this._attachedCamera) {
  78015. return;
  78016. }
  78017. // Add the bounce animation to the lower radius limit
  78018. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  78019. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  78020. }
  78021. // Add the bounce animation to the upper radius limit
  78022. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  78023. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  78024. }
  78025. });
  78026. };
  78027. BouncingBehavior.prototype.detach = function () {
  78028. if (!this._attachedCamera) {
  78029. return;
  78030. }
  78031. if (this._onAfterCheckInputsObserver) {
  78032. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  78033. }
  78034. if (this._onMeshTargetChangedObserver) {
  78035. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  78036. }
  78037. this._attachedCamera = null;
  78038. };
  78039. /**
  78040. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  78041. * @param radiusLimit The limit to check against.
  78042. * @return Bool to indicate if at limit.
  78043. */
  78044. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  78045. if (!this._attachedCamera) {
  78046. return false;
  78047. }
  78048. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  78049. return true;
  78050. }
  78051. return false;
  78052. };
  78053. /**
  78054. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  78055. * @param radiusDelta The delta by which to animate to. Can be negative.
  78056. */
  78057. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  78058. var _this = this;
  78059. if (!this._attachedCamera) {
  78060. return;
  78061. }
  78062. if (!this._radiusBounceTransition) {
  78063. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  78064. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  78065. }
  78066. // Prevent zoom until bounce has completed
  78067. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  78068. this._attachedCamera.wheelPrecision = Infinity;
  78069. this._attachedCamera.inertialRadiusOffset = 0;
  78070. // Animate to the radius limit
  78071. this.stopAllAnimations();
  78072. this._radiusIsAnimating = true;
  78073. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  78074. if (animatable) {
  78075. this._animatables.push(animatable);
  78076. }
  78077. };
  78078. /**
  78079. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  78080. */
  78081. BouncingBehavior.prototype._clearAnimationLocks = function () {
  78082. this._radiusIsAnimating = false;
  78083. if (this._attachedCamera) {
  78084. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  78085. }
  78086. };
  78087. /**
  78088. * Stops and removes all animations that have been applied to the camera
  78089. */
  78090. BouncingBehavior.prototype.stopAllAnimations = function () {
  78091. if (this._attachedCamera) {
  78092. this._attachedCamera.animations = [];
  78093. }
  78094. while (this._animatables.length) {
  78095. this._animatables[0].onAnimationEnd = null;
  78096. this._animatables[0].stop();
  78097. this._animatables.shift();
  78098. }
  78099. };
  78100. /**
  78101. * The easing function used by animations
  78102. */
  78103. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  78104. /**
  78105. * The easing mode used by animations
  78106. */
  78107. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  78108. return BouncingBehavior;
  78109. }());
  78110. BABYLON.BouncingBehavior = BouncingBehavior;
  78111. })(BABYLON || (BABYLON = {}));
  78112. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  78113. var BABYLON;
  78114. (function (BABYLON) {
  78115. var AutoRotationBehavior = /** @class */ (function () {
  78116. function AutoRotationBehavior() {
  78117. this._zoomStopsAnimation = false;
  78118. this._idleRotationSpeed = 0.05;
  78119. this._idleRotationWaitTime = 2000;
  78120. this._idleRotationSpinupTime = 2000;
  78121. this._isPointerDown = false;
  78122. this._lastFrameTime = null;
  78123. this._lastInteractionTime = -Infinity;
  78124. this._cameraRotationSpeed = 0;
  78125. this._lastFrameRadius = 0;
  78126. }
  78127. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  78128. get: function () {
  78129. return "AutoRotation";
  78130. },
  78131. enumerable: true,
  78132. configurable: true
  78133. });
  78134. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  78135. /**
  78136. * Gets the flag that indicates if user zooming should stop animation.
  78137. */
  78138. get: function () {
  78139. return this._zoomStopsAnimation;
  78140. },
  78141. /**
  78142. * Sets the flag that indicates if user zooming should stop animation.
  78143. */
  78144. set: function (flag) {
  78145. this._zoomStopsAnimation = flag;
  78146. },
  78147. enumerable: true,
  78148. configurable: true
  78149. });
  78150. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  78151. /**
  78152. * Gets the default speed at which the camera rotates around the model.
  78153. */
  78154. get: function () {
  78155. return this._idleRotationSpeed;
  78156. },
  78157. /**
  78158. * Sets the default speed at which the camera rotates around the model.
  78159. */
  78160. set: function (speed) {
  78161. this._idleRotationSpeed = speed;
  78162. },
  78163. enumerable: true,
  78164. configurable: true
  78165. });
  78166. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  78167. /**
  78168. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  78169. */
  78170. get: function () {
  78171. return this._idleRotationWaitTime;
  78172. },
  78173. /**
  78174. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  78175. */
  78176. set: function (time) {
  78177. this._idleRotationWaitTime = time;
  78178. },
  78179. enumerable: true,
  78180. configurable: true
  78181. });
  78182. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  78183. /**
  78184. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  78185. */
  78186. get: function () {
  78187. return this._idleRotationSpinupTime;
  78188. },
  78189. /**
  78190. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  78191. */
  78192. set: function (time) {
  78193. this._idleRotationSpinupTime = time;
  78194. },
  78195. enumerable: true,
  78196. configurable: true
  78197. });
  78198. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  78199. /**
  78200. * Gets a value indicating if the camera is currently rotating because of this behavior
  78201. */
  78202. get: function () {
  78203. return Math.abs(this._cameraRotationSpeed) > 0;
  78204. },
  78205. enumerable: true,
  78206. configurable: true
  78207. });
  78208. AutoRotationBehavior.prototype.init = function () {
  78209. // Do notihng
  78210. };
  78211. AutoRotationBehavior.prototype.attach = function (camera) {
  78212. var _this = this;
  78213. this._attachedCamera = camera;
  78214. var scene = this._attachedCamera.getScene();
  78215. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  78216. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  78217. _this._isPointerDown = true;
  78218. return;
  78219. }
  78220. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  78221. _this._isPointerDown = false;
  78222. }
  78223. });
  78224. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  78225. var now = BABYLON.Tools.Now;
  78226. var dt = 0;
  78227. if (_this._lastFrameTime != null) {
  78228. dt = now - _this._lastFrameTime;
  78229. }
  78230. _this._lastFrameTime = now;
  78231. // Stop the animation if there is user interaction and the animation should stop for this interaction
  78232. _this._applyUserInteraction();
  78233. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  78234. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  78235. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  78236. // Step camera rotation by rotation speed
  78237. if (_this._attachedCamera) {
  78238. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  78239. }
  78240. });
  78241. };
  78242. AutoRotationBehavior.prototype.detach = function () {
  78243. if (!this._attachedCamera) {
  78244. return;
  78245. }
  78246. var scene = this._attachedCamera.getScene();
  78247. if (this._onPrePointerObservableObserver) {
  78248. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  78249. }
  78250. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  78251. this._attachedCamera = null;
  78252. };
  78253. /**
  78254. * Returns true if user is scrolling.
  78255. * @return true if user is scrolling.
  78256. */
  78257. AutoRotationBehavior.prototype._userIsZooming = function () {
  78258. if (!this._attachedCamera) {
  78259. return false;
  78260. }
  78261. return this._attachedCamera.inertialRadiusOffset !== 0;
  78262. };
  78263. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  78264. if (!this._attachedCamera) {
  78265. return false;
  78266. }
  78267. var zoomHasHitLimit = false;
  78268. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  78269. zoomHasHitLimit = true;
  78270. }
  78271. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  78272. this._lastFrameRadius = this._attachedCamera.radius;
  78273. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  78274. };
  78275. /**
  78276. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  78277. */
  78278. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  78279. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  78280. this._lastInteractionTime = BABYLON.Tools.Now;
  78281. }
  78282. };
  78283. // Tools
  78284. AutoRotationBehavior.prototype._userIsMoving = function () {
  78285. if (!this._attachedCamera) {
  78286. return false;
  78287. }
  78288. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  78289. this._attachedCamera.inertialBetaOffset !== 0 ||
  78290. this._attachedCamera.inertialRadiusOffset !== 0 ||
  78291. this._attachedCamera.inertialPanningX !== 0 ||
  78292. this._attachedCamera.inertialPanningY !== 0 ||
  78293. this._isPointerDown;
  78294. };
  78295. return AutoRotationBehavior;
  78296. }());
  78297. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  78298. })(BABYLON || (BABYLON = {}));
  78299. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  78300. var BABYLON;
  78301. (function (BABYLON) {
  78302. var NullEngineOptions = /** @class */ (function () {
  78303. function NullEngineOptions() {
  78304. this.renderWidth = 512;
  78305. this.renderHeight = 256;
  78306. this.textureSize = 512;
  78307. this.deterministicLockstep = false;
  78308. this.lockstepMaxSteps = 4;
  78309. }
  78310. return NullEngineOptions;
  78311. }());
  78312. BABYLON.NullEngineOptions = NullEngineOptions;
  78313. /**
  78314. * The null engine class provides support for headless version of babylon.js.
  78315. * This can be used in server side scenario or for testing purposes
  78316. */
  78317. var NullEngine = /** @class */ (function (_super) {
  78318. __extends(NullEngine, _super);
  78319. function NullEngine(options) {
  78320. if (options === void 0) { options = new NullEngineOptions(); }
  78321. var _this = _super.call(this, null) || this;
  78322. if (options.deterministicLockstep === undefined) {
  78323. options.deterministicLockstep = false;
  78324. }
  78325. if (options.lockstepMaxSteps === undefined) {
  78326. options.lockstepMaxSteps = 4;
  78327. }
  78328. _this._options = options;
  78329. // Init caps
  78330. // We consider we are on a webgl1 capable device
  78331. _this._caps = new BABYLON.EngineCapabilities();
  78332. _this._caps.maxTexturesImageUnits = 16;
  78333. _this._caps.maxVertexTextureImageUnits = 16;
  78334. _this._caps.maxTextureSize = 512;
  78335. _this._caps.maxCubemapTextureSize = 512;
  78336. _this._caps.maxRenderTextureSize = 512;
  78337. _this._caps.maxVertexAttribs = 16;
  78338. _this._caps.maxVaryingVectors = 16;
  78339. _this._caps.maxFragmentUniformVectors = 16;
  78340. _this._caps.maxVertexUniformVectors = 16;
  78341. // Extensions
  78342. _this._caps.standardDerivatives = false;
  78343. _this._caps.astc = null;
  78344. _this._caps.s3tc = null;
  78345. _this._caps.pvrtc = null;
  78346. _this._caps.etc1 = null;
  78347. _this._caps.etc2 = null;
  78348. _this._caps.textureAnisotropicFilterExtension = null;
  78349. _this._caps.maxAnisotropy = 0;
  78350. _this._caps.uintIndices = false;
  78351. _this._caps.fragmentDepthSupported = false;
  78352. _this._caps.highPrecisionShaderSupported = true;
  78353. _this._caps.colorBufferFloat = false;
  78354. _this._caps.textureFloat = false;
  78355. _this._caps.textureFloatLinearFiltering = false;
  78356. _this._caps.textureFloatRender = false;
  78357. _this._caps.textureHalfFloat = false;
  78358. _this._caps.textureHalfFloatLinearFiltering = false;
  78359. _this._caps.textureHalfFloatRender = false;
  78360. _this._caps.textureLOD = false;
  78361. _this._caps.drawBuffersExtension = false;
  78362. _this._caps.depthTextureExtension = false;
  78363. _this._caps.vertexArrayObject = false;
  78364. _this._caps.instancedArrays = false;
  78365. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  78366. // Wrappers
  78367. if (typeof URL === "undefined") {
  78368. URL = {
  78369. createObjectURL: function () { },
  78370. revokeObjectURL: function () { }
  78371. };
  78372. }
  78373. if (typeof Blob === "undefined") {
  78374. Blob = function () { };
  78375. }
  78376. return _this;
  78377. }
  78378. NullEngine.prototype.isDeterministicLockStep = function () {
  78379. return this._options.deterministicLockstep;
  78380. };
  78381. NullEngine.prototype.getLockstepMaxSteps = function () {
  78382. return this._options.lockstepMaxSteps;
  78383. };
  78384. NullEngine.prototype.createVertexBuffer = function (vertices) {
  78385. return {
  78386. capacity: 0,
  78387. references: 1,
  78388. is32Bits: false
  78389. };
  78390. };
  78391. NullEngine.prototype.createIndexBuffer = function (indices) {
  78392. return {
  78393. capacity: 0,
  78394. references: 1,
  78395. is32Bits: false
  78396. };
  78397. };
  78398. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  78399. if (stencil === void 0) { stencil = false; }
  78400. };
  78401. NullEngine.prototype.getRenderWidth = function (useScreen) {
  78402. if (useScreen === void 0) { useScreen = false; }
  78403. if (!useScreen && this._currentRenderTarget) {
  78404. return this._currentRenderTarget.width;
  78405. }
  78406. return this._options.renderWidth;
  78407. };
  78408. NullEngine.prototype.getRenderHeight = function (useScreen) {
  78409. if (useScreen === void 0) { useScreen = false; }
  78410. if (!useScreen && this._currentRenderTarget) {
  78411. return this._currentRenderTarget.height;
  78412. }
  78413. return this._options.renderHeight;
  78414. };
  78415. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  78416. this._cachedViewport = viewport;
  78417. };
  78418. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  78419. return {
  78420. transformFeedback: null,
  78421. __SPECTOR_rebuildProgram: null
  78422. };
  78423. };
  78424. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  78425. return [];
  78426. };
  78427. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  78428. return [];
  78429. };
  78430. NullEngine.prototype.bindSamplers = function (effect) {
  78431. this._currentEffect = null;
  78432. };
  78433. NullEngine.prototype.enableEffect = function (effect) {
  78434. this._currentEffect = effect;
  78435. if (effect.onBind) {
  78436. effect.onBind(effect);
  78437. }
  78438. effect.onBindObservable.notifyObservers(effect);
  78439. };
  78440. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  78441. if (zOffset === void 0) { zOffset = 0; }
  78442. if (reverseSide === void 0) { reverseSide = false; }
  78443. };
  78444. NullEngine.prototype.setIntArray = function (uniform, array) {
  78445. };
  78446. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  78447. };
  78448. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  78449. };
  78450. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  78451. };
  78452. NullEngine.prototype.setFloatArray = function (uniform, array) {
  78453. };
  78454. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  78455. };
  78456. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  78457. };
  78458. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  78459. };
  78460. NullEngine.prototype.setArray = function (uniform, array) {
  78461. };
  78462. NullEngine.prototype.setArray2 = function (uniform, array) {
  78463. };
  78464. NullEngine.prototype.setArray3 = function (uniform, array) {
  78465. };
  78466. NullEngine.prototype.setArray4 = function (uniform, array) {
  78467. };
  78468. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  78469. };
  78470. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  78471. };
  78472. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  78473. };
  78474. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  78475. };
  78476. NullEngine.prototype.setFloat = function (uniform, value) {
  78477. };
  78478. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  78479. };
  78480. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  78481. };
  78482. NullEngine.prototype.setBool = function (uniform, bool) {
  78483. };
  78484. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  78485. };
  78486. NullEngine.prototype.setColor3 = function (uniform, color3) {
  78487. };
  78488. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  78489. };
  78490. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  78491. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  78492. if (this._alphaMode === mode) {
  78493. return;
  78494. }
  78495. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  78496. if (!noDepthWriteChange) {
  78497. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  78498. }
  78499. this._alphaMode = mode;
  78500. };
  78501. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  78502. };
  78503. NullEngine.prototype.wipeCaches = function (bruteForce) {
  78504. if (this.preventCacheWipeBetweenFrames) {
  78505. return;
  78506. }
  78507. this.resetTextureCache();
  78508. this._currentEffect = null;
  78509. if (bruteForce) {
  78510. this._currentProgram = null;
  78511. this._stencilState.reset();
  78512. this._depthCullingState.reset();
  78513. this.setDepthFunctionToLessOrEqual();
  78514. this._alphaState.reset();
  78515. }
  78516. this._cachedVertexBuffers = null;
  78517. this._cachedIndexBuffer = null;
  78518. this._cachedEffectForVertexBuffers = null;
  78519. };
  78520. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  78521. };
  78522. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  78523. };
  78524. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  78525. };
  78526. NullEngine.prototype._createTexture = function () {
  78527. return {};
  78528. };
  78529. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  78530. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  78531. if (onLoad === void 0) { onLoad = null; }
  78532. if (onError === void 0) { onError = null; }
  78533. if (buffer === void 0) { buffer = null; }
  78534. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  78535. var url = String(urlArg);
  78536. texture.url = url;
  78537. texture.generateMipMaps = !noMipmap;
  78538. texture.samplingMode = samplingMode;
  78539. texture.invertY = invertY;
  78540. texture.baseWidth = this._options.textureSize;
  78541. texture.baseHeight = this._options.textureSize;
  78542. texture.width = this._options.textureSize;
  78543. texture.height = this._options.textureSize;
  78544. if (format) {
  78545. texture.format = format;
  78546. }
  78547. texture.isReady = true;
  78548. if (onLoad) {
  78549. onLoad();
  78550. }
  78551. return texture;
  78552. };
  78553. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  78554. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  78555. if (options !== undefined && typeof options === "object") {
  78556. fullOptions.generateMipMaps = options.generateMipMaps;
  78557. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  78558. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  78559. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  78560. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  78561. }
  78562. else {
  78563. fullOptions.generateMipMaps = options;
  78564. fullOptions.generateDepthBuffer = true;
  78565. fullOptions.generateStencilBuffer = false;
  78566. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  78567. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  78568. }
  78569. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  78570. var width = size.width || size;
  78571. var height = size.height || size;
  78572. texture._depthStencilBuffer = {};
  78573. texture._framebuffer = {};
  78574. texture.baseWidth = width;
  78575. texture.baseHeight = height;
  78576. texture.width = width;
  78577. texture.height = height;
  78578. texture.isReady = true;
  78579. texture.samples = 1;
  78580. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  78581. texture.samplingMode = fullOptions.samplingMode;
  78582. texture.type = fullOptions.type;
  78583. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  78584. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  78585. return texture;
  78586. };
  78587. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  78588. texture.samplingMode = samplingMode;
  78589. };
  78590. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  78591. if (this._currentRenderTarget) {
  78592. this.unBindFramebuffer(this._currentRenderTarget);
  78593. }
  78594. this._currentRenderTarget = texture;
  78595. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  78596. if (this._cachedViewport && !forceFullscreenViewport) {
  78597. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  78598. }
  78599. };
  78600. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  78601. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  78602. this._currentRenderTarget = null;
  78603. if (onBeforeUnbind) {
  78604. if (texture._MSAAFramebuffer) {
  78605. this._currentFramebuffer = texture._framebuffer;
  78606. }
  78607. onBeforeUnbind();
  78608. }
  78609. this._currentFramebuffer = null;
  78610. };
  78611. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  78612. var vbo = {
  78613. capacity: 1,
  78614. references: 1,
  78615. is32Bits: false
  78616. };
  78617. return vbo;
  78618. };
  78619. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  78620. if (offset === void 0) { offset = 0; }
  78621. };
  78622. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  78623. };
  78624. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  78625. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  78626. this._boundTexturesCache[this._activeChannel] = texture;
  78627. }
  78628. };
  78629. NullEngine.prototype._bindTexture = function (channel, texture) {
  78630. if (channel < 0) {
  78631. return;
  78632. }
  78633. this._bindTextureDirectly(0, texture);
  78634. };
  78635. NullEngine.prototype._releaseBuffer = function (buffer) {
  78636. buffer.references--;
  78637. if (buffer.references === 0) {
  78638. return true;
  78639. }
  78640. return false;
  78641. };
  78642. return NullEngine;
  78643. }(BABYLON.Engine));
  78644. BABYLON.NullEngine = NullEngine;
  78645. })(BABYLON || (BABYLON = {}));
  78646. //# sourceMappingURL=babylon.nullEngine.js.map
  78647. var BABYLON;
  78648. (function (BABYLON) {
  78649. /**
  78650. * This class can be used to get instrumentation data from a Babylon engine
  78651. */
  78652. var EngineInstrumentation = /** @class */ (function () {
  78653. function EngineInstrumentation(engine) {
  78654. this.engine = engine;
  78655. this._captureGPUFrameTime = false;
  78656. this._gpuFrameTime = new BABYLON.PerfCounter();
  78657. this._captureShaderCompilationTime = false;
  78658. this._shaderCompilationTime = new BABYLON.PerfCounter();
  78659. // Observers
  78660. this._onBeginFrameObserver = null;
  78661. this._onEndFrameObserver = null;
  78662. this._onBeforeShaderCompilationObserver = null;
  78663. this._onAfterShaderCompilationObserver = null;
  78664. }
  78665. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  78666. // Properties
  78667. /**
  78668. * Gets the perf counter used for GPU frame time
  78669. */
  78670. get: function () {
  78671. return this._gpuFrameTime;
  78672. },
  78673. enumerable: true,
  78674. configurable: true
  78675. });
  78676. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  78677. /**
  78678. * Gets the GPU frame time capture status
  78679. */
  78680. get: function () {
  78681. return this._captureGPUFrameTime;
  78682. },
  78683. /**
  78684. * Enable or disable the GPU frame time capture
  78685. */
  78686. set: function (value) {
  78687. var _this = this;
  78688. if (value === this._captureGPUFrameTime) {
  78689. return;
  78690. }
  78691. this._captureGPUFrameTime = value;
  78692. if (value) {
  78693. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  78694. if (!_this._gpuFrameTimeToken) {
  78695. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  78696. }
  78697. });
  78698. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  78699. if (!_this._gpuFrameTimeToken) {
  78700. return;
  78701. }
  78702. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  78703. if (time > -1) {
  78704. _this._gpuFrameTimeToken = null;
  78705. _this._gpuFrameTime.fetchNewFrame();
  78706. _this._gpuFrameTime.addCount(time, true);
  78707. }
  78708. });
  78709. }
  78710. else {
  78711. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  78712. this._onBeginFrameObserver = null;
  78713. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  78714. this._onEndFrameObserver = null;
  78715. }
  78716. },
  78717. enumerable: true,
  78718. configurable: true
  78719. });
  78720. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  78721. /**
  78722. * Gets the perf counter used for shader compilation time
  78723. */
  78724. get: function () {
  78725. return this._shaderCompilationTime;
  78726. },
  78727. enumerable: true,
  78728. configurable: true
  78729. });
  78730. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  78731. /**
  78732. * Gets the shader compilation time capture status
  78733. */
  78734. get: function () {
  78735. return this._captureShaderCompilationTime;
  78736. },
  78737. /**
  78738. * Enable or disable the shader compilation time capture
  78739. */
  78740. set: function (value) {
  78741. var _this = this;
  78742. if (value === this._captureShaderCompilationTime) {
  78743. return;
  78744. }
  78745. this._captureShaderCompilationTime = value;
  78746. if (value) {
  78747. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  78748. _this._shaderCompilationTime.fetchNewFrame();
  78749. _this._shaderCompilationTime.beginMonitoring();
  78750. });
  78751. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  78752. _this._shaderCompilationTime.endMonitoring();
  78753. });
  78754. }
  78755. else {
  78756. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  78757. this._onBeforeShaderCompilationObserver = null;
  78758. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  78759. this._onAfterShaderCompilationObserver = null;
  78760. }
  78761. },
  78762. enumerable: true,
  78763. configurable: true
  78764. });
  78765. EngineInstrumentation.prototype.dispose = function () {
  78766. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  78767. this._onBeginFrameObserver = null;
  78768. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  78769. this._onEndFrameObserver = null;
  78770. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  78771. this._onBeforeShaderCompilationObserver = null;
  78772. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  78773. this._onAfterShaderCompilationObserver = null;
  78774. this.engine = null;
  78775. };
  78776. return EngineInstrumentation;
  78777. }());
  78778. BABYLON.EngineInstrumentation = EngineInstrumentation;
  78779. })(BABYLON || (BABYLON = {}));
  78780. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  78781. var BABYLON;
  78782. (function (BABYLON) {
  78783. /**
  78784. * This class can be used to get instrumentation data from a Babylon engine
  78785. */
  78786. var SceneInstrumentation = /** @class */ (function () {
  78787. function SceneInstrumentation(scene) {
  78788. var _this = this;
  78789. this.scene = scene;
  78790. this._captureActiveMeshesEvaluationTime = false;
  78791. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  78792. this._captureRenderTargetsRenderTime = false;
  78793. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  78794. this._captureFrameTime = false;
  78795. this._frameTime = new BABYLON.PerfCounter();
  78796. this._captureRenderTime = false;
  78797. this._renderTime = new BABYLON.PerfCounter();
  78798. this._captureInterFrameTime = false;
  78799. this._interFrameTime = new BABYLON.PerfCounter();
  78800. this._captureParticlesRenderTime = false;
  78801. this._particlesRenderTime = new BABYLON.PerfCounter();
  78802. this._captureSpritesRenderTime = false;
  78803. this._spritesRenderTime = new BABYLON.PerfCounter();
  78804. this._capturePhysicsTime = false;
  78805. this._physicsTime = new BABYLON.PerfCounter();
  78806. this._captureAnimationsTime = false;
  78807. this._animationsTime = new BABYLON.PerfCounter();
  78808. // Observers
  78809. this._onBeforeActiveMeshesEvaluationObserver = null;
  78810. this._onAfterActiveMeshesEvaluationObserver = null;
  78811. this._onBeforeRenderTargetsRenderObserver = null;
  78812. this._onAfterRenderTargetsRenderObserver = null;
  78813. this._onAfterRenderObserver = null;
  78814. this._onBeforeDrawPhaseObserver = null;
  78815. this._onAfterDrawPhaseObserver = null;
  78816. this._onBeforeAnimationsObserver = null;
  78817. this._onBeforeParticlesRenderingObserver = null;
  78818. this._onAfterParticlesRenderingObserver = null;
  78819. this._onBeforeSpritesRenderingObserver = null;
  78820. this._onAfterSpritesRenderingObserver = null;
  78821. this._onBeforePhysicsObserver = null;
  78822. this._onAfterPhysicsObserver = null;
  78823. this._onAfterAnimationsObserver = null;
  78824. // Before render
  78825. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  78826. if (_this._captureActiveMeshesEvaluationTime) {
  78827. _this._activeMeshesEvaluationTime.fetchNewFrame();
  78828. }
  78829. if (_this._captureRenderTargetsRenderTime) {
  78830. _this._renderTargetsRenderTime.fetchNewFrame();
  78831. }
  78832. if (_this._captureFrameTime) {
  78833. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  78834. _this._frameTime.beginMonitoring();
  78835. }
  78836. if (_this._captureInterFrameTime) {
  78837. _this._interFrameTime.endMonitoring();
  78838. }
  78839. if (_this._captureParticlesRenderTime) {
  78840. _this._particlesRenderTime.fetchNewFrame();
  78841. }
  78842. if (_this._captureSpritesRenderTime) {
  78843. _this._spritesRenderTime.fetchNewFrame();
  78844. }
  78845. if (_this._captureAnimationsTime) {
  78846. _this._animationsTime.beginMonitoring();
  78847. }
  78848. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  78849. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  78850. });
  78851. // After render
  78852. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  78853. if (_this._captureFrameTime) {
  78854. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  78855. _this._frameTime.endMonitoring();
  78856. }
  78857. if (_this._captureRenderTime) {
  78858. _this._renderTime.endMonitoring(false);
  78859. }
  78860. if (_this._captureInterFrameTime) {
  78861. _this._interFrameTime.beginMonitoring();
  78862. }
  78863. });
  78864. }
  78865. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  78866. // Properties
  78867. /**
  78868. * Gets the perf counter used for active meshes evaluation time
  78869. */
  78870. get: function () {
  78871. return this._activeMeshesEvaluationTime;
  78872. },
  78873. enumerable: true,
  78874. configurable: true
  78875. });
  78876. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  78877. /**
  78878. * Gets the active meshes evaluation time capture status
  78879. */
  78880. get: function () {
  78881. return this._captureActiveMeshesEvaluationTime;
  78882. },
  78883. /**
  78884. * Enable or disable the active meshes evaluation time capture
  78885. */
  78886. set: function (value) {
  78887. var _this = this;
  78888. if (value === this._captureActiveMeshesEvaluationTime) {
  78889. return;
  78890. }
  78891. this._captureActiveMeshesEvaluationTime = value;
  78892. if (value) {
  78893. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  78894. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  78895. _this._activeMeshesEvaluationTime.beginMonitoring();
  78896. });
  78897. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  78898. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  78899. _this._activeMeshesEvaluationTime.endMonitoring();
  78900. });
  78901. }
  78902. else {
  78903. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  78904. this._onBeforeActiveMeshesEvaluationObserver = null;
  78905. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  78906. this._onAfterActiveMeshesEvaluationObserver = null;
  78907. }
  78908. },
  78909. enumerable: true,
  78910. configurable: true
  78911. });
  78912. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  78913. /**
  78914. * Gets the perf counter used for render targets render time
  78915. */
  78916. get: function () {
  78917. return this._renderTargetsRenderTime;
  78918. },
  78919. enumerable: true,
  78920. configurable: true
  78921. });
  78922. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  78923. /**
  78924. * Gets the render targets render time capture status
  78925. */
  78926. get: function () {
  78927. return this._captureRenderTargetsRenderTime;
  78928. },
  78929. /**
  78930. * Enable or disable the render targets render time capture
  78931. */
  78932. set: function (value) {
  78933. var _this = this;
  78934. if (value === this._captureRenderTargetsRenderTime) {
  78935. return;
  78936. }
  78937. this._captureRenderTargetsRenderTime = value;
  78938. if (value) {
  78939. this._onBeforeRenderTargetsRenderObserver = this.scene.OnBeforeRenderTargetsRenderObservable.add(function () {
  78940. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  78941. _this._renderTargetsRenderTime.beginMonitoring();
  78942. });
  78943. this._onAfterRenderTargetsRenderObserver = this.scene.OnAfterRenderTargetsRenderObservable.add(function () {
  78944. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  78945. _this._renderTargetsRenderTime.endMonitoring(false);
  78946. });
  78947. }
  78948. else {
  78949. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  78950. this._onBeforeRenderTargetsRenderObserver = null;
  78951. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  78952. this._onAfterRenderTargetsRenderObserver = null;
  78953. }
  78954. },
  78955. enumerable: true,
  78956. configurable: true
  78957. });
  78958. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  78959. /**
  78960. * Gets the perf counter used for particles render time
  78961. */
  78962. get: function () {
  78963. return this._particlesRenderTime;
  78964. },
  78965. enumerable: true,
  78966. configurable: true
  78967. });
  78968. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  78969. /**
  78970. * Gets the particles render time capture status
  78971. */
  78972. get: function () {
  78973. return this._captureParticlesRenderTime;
  78974. },
  78975. /**
  78976. * Enable or disable the particles render time capture
  78977. */
  78978. set: function (value) {
  78979. var _this = this;
  78980. if (value === this._captureParticlesRenderTime) {
  78981. return;
  78982. }
  78983. this._captureParticlesRenderTime = value;
  78984. if (value) {
  78985. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  78986. BABYLON.Tools.StartPerformanceCounter("Particles");
  78987. _this._particlesRenderTime.beginMonitoring();
  78988. });
  78989. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  78990. BABYLON.Tools.EndPerformanceCounter("Particles");
  78991. _this._particlesRenderTime.endMonitoring(false);
  78992. });
  78993. }
  78994. else {
  78995. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  78996. this._onBeforeParticlesRenderingObserver = null;
  78997. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  78998. this._onAfterParticlesRenderingObserver = null;
  78999. }
  79000. },
  79001. enumerable: true,
  79002. configurable: true
  79003. });
  79004. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  79005. /**
  79006. * Gets the perf counter used for sprites render time
  79007. */
  79008. get: function () {
  79009. return this._spritesRenderTime;
  79010. },
  79011. enumerable: true,
  79012. configurable: true
  79013. });
  79014. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  79015. /**
  79016. * Gets the sprites render time capture status
  79017. */
  79018. get: function () {
  79019. return this._captureSpritesRenderTime;
  79020. },
  79021. /**
  79022. * Enable or disable the sprites render time capture
  79023. */
  79024. set: function (value) {
  79025. var _this = this;
  79026. if (value === this._captureSpritesRenderTime) {
  79027. return;
  79028. }
  79029. this._captureSpritesRenderTime = value;
  79030. if (value) {
  79031. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  79032. BABYLON.Tools.StartPerformanceCounter("Sprites");
  79033. _this._spritesRenderTime.beginMonitoring();
  79034. });
  79035. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  79036. BABYLON.Tools.EndPerformanceCounter("Sprites");
  79037. _this._spritesRenderTime.endMonitoring(false);
  79038. });
  79039. }
  79040. else {
  79041. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  79042. this._onBeforeSpritesRenderingObserver = null;
  79043. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  79044. this._onAfterSpritesRenderingObserver = null;
  79045. }
  79046. },
  79047. enumerable: true,
  79048. configurable: true
  79049. });
  79050. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  79051. /**
  79052. * Gets the perf counter used for physics time
  79053. */
  79054. get: function () {
  79055. return this._physicsTime;
  79056. },
  79057. enumerable: true,
  79058. configurable: true
  79059. });
  79060. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  79061. /**
  79062. * Gets the physics time capture status
  79063. */
  79064. get: function () {
  79065. return this._capturePhysicsTime;
  79066. },
  79067. /**
  79068. * Enable or disable the physics time capture
  79069. */
  79070. set: function (value) {
  79071. var _this = this;
  79072. if (value === this._capturePhysicsTime) {
  79073. return;
  79074. }
  79075. this._capturePhysicsTime = value;
  79076. if (value) {
  79077. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  79078. BABYLON.Tools.StartPerformanceCounter("Physics");
  79079. _this._physicsTime.beginMonitoring();
  79080. });
  79081. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  79082. BABYLON.Tools.EndPerformanceCounter("Physics");
  79083. _this._physicsTime.endMonitoring();
  79084. });
  79085. }
  79086. else {
  79087. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  79088. this._onBeforePhysicsObserver = null;
  79089. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  79090. this._onAfterPhysicsObserver = null;
  79091. }
  79092. },
  79093. enumerable: true,
  79094. configurable: true
  79095. });
  79096. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  79097. /**
  79098. * Gets the perf counter used for animations time
  79099. */
  79100. get: function () {
  79101. return this._animationsTime;
  79102. },
  79103. enumerable: true,
  79104. configurable: true
  79105. });
  79106. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  79107. /**
  79108. * Gets the animations time capture status
  79109. */
  79110. get: function () {
  79111. return this._captureAnimationsTime;
  79112. },
  79113. /**
  79114. * Enable or disable the animations time capture
  79115. */
  79116. set: function (value) {
  79117. var _this = this;
  79118. if (value === this._captureAnimationsTime) {
  79119. return;
  79120. }
  79121. this._captureAnimationsTime = value;
  79122. if (value) {
  79123. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  79124. _this._animationsTime.endMonitoring();
  79125. });
  79126. }
  79127. else {
  79128. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  79129. this._onAfterAnimationsObserver = null;
  79130. }
  79131. },
  79132. enumerable: true,
  79133. configurable: true
  79134. });
  79135. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  79136. /**
  79137. * Gets the perf counter used for frame time capture
  79138. */
  79139. get: function () {
  79140. return this._frameTime;
  79141. },
  79142. enumerable: true,
  79143. configurable: true
  79144. });
  79145. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  79146. /**
  79147. * Gets the frame time capture status
  79148. */
  79149. get: function () {
  79150. return this._captureFrameTime;
  79151. },
  79152. /**
  79153. * Enable or disable the frame time capture
  79154. */
  79155. set: function (value) {
  79156. this._captureFrameTime = value;
  79157. },
  79158. enumerable: true,
  79159. configurable: true
  79160. });
  79161. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  79162. /**
  79163. * Gets the perf counter used for inter-frames time capture
  79164. */
  79165. get: function () {
  79166. return this._interFrameTime;
  79167. },
  79168. enumerable: true,
  79169. configurable: true
  79170. });
  79171. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  79172. /**
  79173. * Gets the inter-frames time capture status
  79174. */
  79175. get: function () {
  79176. return this._captureInterFrameTime;
  79177. },
  79178. /**
  79179. * Enable or disable the inter-frames time capture
  79180. */
  79181. set: function (value) {
  79182. this._captureInterFrameTime = value;
  79183. },
  79184. enumerable: true,
  79185. configurable: true
  79186. });
  79187. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  79188. /**
  79189. * Gets the perf counter used for render time capture
  79190. */
  79191. get: function () {
  79192. return this._renderTime;
  79193. },
  79194. enumerable: true,
  79195. configurable: true
  79196. });
  79197. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  79198. /**
  79199. * Gets the render time capture status
  79200. */
  79201. get: function () {
  79202. return this._captureRenderTime;
  79203. },
  79204. /**
  79205. * Enable or disable the render time capture
  79206. */
  79207. set: function (value) {
  79208. var _this = this;
  79209. if (value === this._captureRenderTime) {
  79210. return;
  79211. }
  79212. this._captureRenderTime = value;
  79213. if (value) {
  79214. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  79215. _this._renderTime.beginMonitoring();
  79216. BABYLON.Tools.StartPerformanceCounter("Main render");
  79217. });
  79218. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  79219. _this._renderTime.endMonitoring(false);
  79220. BABYLON.Tools.EndPerformanceCounter("Main render");
  79221. });
  79222. }
  79223. else {
  79224. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  79225. this._onBeforeDrawPhaseObserver = null;
  79226. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  79227. this._onAfterDrawPhaseObserver = null;
  79228. }
  79229. },
  79230. enumerable: true,
  79231. configurable: true
  79232. });
  79233. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  79234. /**
  79235. * Gets the perf counter used for draw calls
  79236. */
  79237. get: function () {
  79238. return this.scene.getEngine()._drawCalls;
  79239. },
  79240. enumerable: true,
  79241. configurable: true
  79242. });
  79243. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  79244. /**
  79245. * Gets the perf counter used for texture collisions
  79246. */
  79247. get: function () {
  79248. return this.scene.getEngine()._textureCollisions;
  79249. },
  79250. enumerable: true,
  79251. configurable: true
  79252. });
  79253. SceneInstrumentation.prototype.dispose = function () {
  79254. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  79255. this._onAfterRenderObserver = null;
  79256. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  79257. this._onBeforeActiveMeshesEvaluationObserver = null;
  79258. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  79259. this._onAfterActiveMeshesEvaluationObserver = null;
  79260. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  79261. this._onBeforeRenderTargetsRenderObserver = null;
  79262. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  79263. this._onAfterRenderTargetsRenderObserver = null;
  79264. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  79265. this._onBeforeAnimationsObserver = null;
  79266. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  79267. this._onBeforeParticlesRenderingObserver = null;
  79268. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  79269. this._onAfterParticlesRenderingObserver = null;
  79270. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  79271. this._onBeforeSpritesRenderingObserver = null;
  79272. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  79273. this._onAfterSpritesRenderingObserver = null;
  79274. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  79275. this._onBeforeDrawPhaseObserver = null;
  79276. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  79277. this._onAfterDrawPhaseObserver = null;
  79278. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  79279. this._onBeforePhysicsObserver = null;
  79280. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  79281. this._onAfterPhysicsObserver = null;
  79282. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  79283. this._onAfterAnimationsObserver = null;
  79284. this.scene = null;
  79285. };
  79286. return SceneInstrumentation;
  79287. }());
  79288. BABYLON.SceneInstrumentation = SceneInstrumentation;
  79289. })(BABYLON || (BABYLON = {}));
  79290. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  79291. var BABYLON;
  79292. (function (BABYLON) {
  79293. var _TimeToken = /** @class */ (function () {
  79294. function _TimeToken() {
  79295. this._timeElapsedQueryEnded = false;
  79296. }
  79297. return _TimeToken;
  79298. }());
  79299. BABYLON._TimeToken = _TimeToken;
  79300. })(BABYLON || (BABYLON = {}));
  79301. //# sourceMappingURL=babylon.timeToken.js.map
  79302. var BABYLON;
  79303. (function (BABYLON) {
  79304. /**
  79305. * Background material defines definition.
  79306. */
  79307. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  79308. __extends(BackgroundMaterialDefines, _super);
  79309. /**
  79310. * Constructor of the defines.
  79311. */
  79312. function BackgroundMaterialDefines() {
  79313. var _this = _super.call(this) || this;
  79314. /**
  79315. * True if the diffuse texture is in use.
  79316. */
  79317. _this.DIFFUSE = false;
  79318. /**
  79319. * The direct UV channel to use.
  79320. */
  79321. _this.DIFFUSEDIRECTUV = 0;
  79322. /**
  79323. * True if the diffuse texture is in gamma space.
  79324. */
  79325. _this.GAMMADIFFUSE = false;
  79326. /**
  79327. * True if the diffuse texture has opacity in the alpha channel.
  79328. */
  79329. _this.DIFFUSEHASALPHA = false;
  79330. /**
  79331. * True if you want the material to fade to transparent at grazing angle.
  79332. */
  79333. _this.OPACITYFRESNEL = false;
  79334. /**
  79335. * True if an extra blur needs to be added in the reflection.
  79336. */
  79337. _this.REFLECTIONBLUR = false;
  79338. /**
  79339. * True if you want the material to fade to reflection at grazing angle.
  79340. */
  79341. _this.REFLECTIONFRESNEL = false;
  79342. /**
  79343. * True if you want the material to falloff as far as you move away from the scene center.
  79344. */
  79345. _this.REFLECTIONFALLOFF = false;
  79346. /**
  79347. * False if the current Webgl implementation does not support the texture lod extension.
  79348. */
  79349. _this.TEXTURELODSUPPORT = false;
  79350. /**
  79351. * True to ensure the data are premultiplied.
  79352. */
  79353. _this.PREMULTIPLYALPHA = false;
  79354. /**
  79355. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  79356. */
  79357. _this.USERGBCOLOR = false;
  79358. /**
  79359. * True to add noise in order to reduce the banding effect.
  79360. */
  79361. _this.NOISE = false;
  79362. // Image Processing Configuration.
  79363. _this.IMAGEPROCESSING = false;
  79364. _this.VIGNETTE = false;
  79365. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  79366. _this.VIGNETTEBLENDMODEOPAQUE = false;
  79367. _this.TONEMAPPING = false;
  79368. _this.CONTRAST = false;
  79369. _this.COLORCURVES = false;
  79370. _this.COLORGRADING = false;
  79371. _this.COLORGRADING3D = false;
  79372. _this.SAMPLER3DGREENDEPTH = false;
  79373. _this.SAMPLER3DBGRMAP = false;
  79374. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  79375. _this.EXPOSURE = false;
  79376. // Reflection.
  79377. _this.REFLECTION = false;
  79378. _this.REFLECTIONMAP_3D = false;
  79379. _this.REFLECTIONMAP_SPHERICAL = false;
  79380. _this.REFLECTIONMAP_PLANAR = false;
  79381. _this.REFLECTIONMAP_CUBIC = false;
  79382. _this.REFLECTIONMAP_PROJECTION = false;
  79383. _this.REFLECTIONMAP_SKYBOX = false;
  79384. _this.REFLECTIONMAP_EXPLICIT = false;
  79385. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  79386. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  79387. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  79388. _this.INVERTCUBICMAP = false;
  79389. _this.REFLECTIONMAP_OPPOSITEZ = false;
  79390. _this.LODINREFLECTIONALPHA = false;
  79391. _this.GAMMAREFLECTION = false;
  79392. // Default BJS.
  79393. _this.MAINUV1 = false;
  79394. _this.MAINUV2 = false;
  79395. _this.UV1 = false;
  79396. _this.UV2 = false;
  79397. _this.CLIPPLANE = false;
  79398. _this.POINTSIZE = false;
  79399. _this.FOG = false;
  79400. _this.NORMAL = false;
  79401. _this.NUM_BONE_INFLUENCERS = 0;
  79402. _this.BonesPerMesh = 0;
  79403. _this.INSTANCES = false;
  79404. _this.SHADOWFLOAT = false;
  79405. _this.rebuild();
  79406. return _this;
  79407. }
  79408. return BackgroundMaterialDefines;
  79409. }(BABYLON.MaterialDefines));
  79410. /**
  79411. * Background material used to create an efficient environement around your scene.
  79412. */
  79413. var BackgroundMaterial = /** @class */ (function (_super) {
  79414. __extends(BackgroundMaterial, _super);
  79415. /**
  79416. * constructor
  79417. * @param name The name of the material
  79418. * @param scene The scene to add the material to
  79419. */
  79420. function BackgroundMaterial(name, scene) {
  79421. var _this = _super.call(this, name, scene) || this;
  79422. _this.primaryColor = BABYLON.Color3.White();
  79423. _this.primaryLevel = 1;
  79424. _this.secondaryColor = BABYLON.Color3.Gray();
  79425. _this.secondaryLevel = 1;
  79426. _this.tertiaryColor = BABYLON.Color3.Black();
  79427. _this.tertiaryLevel = 1;
  79428. _this.reflectionTexture = null;
  79429. _this.reflectionBlur = 0;
  79430. _this.diffuseTexture = null;
  79431. /**
  79432. * Specify the list of lights casting shadow on the material.
  79433. * All scene shadow lights will be included if null.
  79434. */
  79435. _this._shadowLights = null;
  79436. _this.shadowLights = null;
  79437. _this.shadowBlurScale = 1;
  79438. _this.shadowLevel = 0;
  79439. _this.sceneCenter = BABYLON.Vector3.Zero();
  79440. _this.opacityFresnel = true;
  79441. _this.reflectionFresnel = false;
  79442. _this.reflectionFalloffDistance = 0.0;
  79443. _this.reflectionAmount = 1.0;
  79444. _this.reflectionReflectance0 = 0.05;
  79445. _this.reflectionReflectance90 = 0.5;
  79446. _this.useRGBColor = true;
  79447. _this.enableNoise = false;
  79448. /**
  79449. * Number of Simultaneous lights allowed on the material.
  79450. */
  79451. _this._maxSimultaneousLights = 4;
  79452. _this.maxSimultaneousLights = 4;
  79453. /**
  79454. * Keep track of the image processing observer to allow dispose and replace.
  79455. */
  79456. _this._imageProcessingObserver = null;
  79457. // Temp values kept as cache in the material.
  79458. _this._renderTargets = new BABYLON.SmartArray(16);
  79459. _this._reflectionControls = BABYLON.Vector4.Zero();
  79460. // Setup the default processing configuration to the scene.
  79461. _this._attachImageProcessingConfiguration(null);
  79462. _this.getRenderTargetTextures = function () {
  79463. _this._renderTargets.reset();
  79464. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  79465. _this._renderTargets.push(_this._diffuseTexture);
  79466. }
  79467. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  79468. _this._renderTargets.push(_this._reflectionTexture);
  79469. }
  79470. return _this._renderTargets;
  79471. };
  79472. return _this;
  79473. }
  79474. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  79475. /**
  79476. * Sets the reflection reflectance fresnel values according to the default standard
  79477. * empirically know to work well :-)
  79478. */
  79479. set: function (value) {
  79480. var reflectionWeight = value;
  79481. if (reflectionWeight < 0.5) {
  79482. reflectionWeight = reflectionWeight * 2.0;
  79483. this.reflectionReflectance0 = BackgroundMaterial.standardReflectance0 * reflectionWeight;
  79484. this.reflectionReflectance90 = BackgroundMaterial.standardReflectance90 * reflectionWeight;
  79485. }
  79486. else {
  79487. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  79488. this.reflectionReflectance0 = BackgroundMaterial.standardReflectance0 + (1.0 - BackgroundMaterial.standardReflectance0) * reflectionWeight;
  79489. this.reflectionReflectance90 = BackgroundMaterial.standardReflectance90 + (1.0 - BackgroundMaterial.standardReflectance90) * reflectionWeight;
  79490. }
  79491. },
  79492. enumerable: true,
  79493. configurable: true
  79494. });
  79495. /**
  79496. * Attaches a new image processing configuration to the PBR Material.
  79497. * @param configuration (if null the scene configuration will be use)
  79498. */
  79499. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  79500. var _this = this;
  79501. if (configuration === this._imageProcessingConfiguration) {
  79502. return;
  79503. }
  79504. // Detaches observer.
  79505. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  79506. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  79507. }
  79508. // Pick the scene configuration if needed.
  79509. if (!configuration) {
  79510. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  79511. }
  79512. else {
  79513. this._imageProcessingConfiguration = configuration;
  79514. }
  79515. // Attaches observer.
  79516. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  79517. _this._markAllSubMeshesAsImageProcessingDirty();
  79518. });
  79519. };
  79520. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  79521. /**
  79522. * Gets the image processing configuration used either in this material.
  79523. */
  79524. get: function () {
  79525. return this._imageProcessingConfiguration;
  79526. },
  79527. /**
  79528. * Sets the Default image processing configuration used either in the this material.
  79529. *
  79530. * If sets to null, the scene one is in use.
  79531. */
  79532. set: function (value) {
  79533. this._attachImageProcessingConfiguration(value);
  79534. // Ensure the effect will be rebuilt.
  79535. this._markAllSubMeshesAsTexturesDirty();
  79536. },
  79537. enumerable: true,
  79538. configurable: true
  79539. });
  79540. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  79541. /**
  79542. * Gets wether the color curves effect is enabled.
  79543. */
  79544. get: function () {
  79545. return this.imageProcessingConfiguration.colorCurvesEnabled;
  79546. },
  79547. /**
  79548. * Sets wether the color curves effect is enabled.
  79549. */
  79550. set: function (value) {
  79551. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  79552. },
  79553. enumerable: true,
  79554. configurable: true
  79555. });
  79556. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  79557. /**
  79558. * Gets wether the color grading effect is enabled.
  79559. */
  79560. get: function () {
  79561. return this.imageProcessingConfiguration.colorGradingEnabled;
  79562. },
  79563. /**
  79564. * Gets wether the color grading effect is enabled.
  79565. */
  79566. set: function (value) {
  79567. this.imageProcessingConfiguration.colorGradingEnabled = value;
  79568. },
  79569. enumerable: true,
  79570. configurable: true
  79571. });
  79572. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  79573. /**
  79574. * Gets wether tonemapping is enabled or not.
  79575. */
  79576. get: function () {
  79577. return this._imageProcessingConfiguration.toneMappingEnabled;
  79578. },
  79579. /**
  79580. * Sets wether tonemapping is enabled or not
  79581. */
  79582. set: function (value) {
  79583. this._imageProcessingConfiguration.toneMappingEnabled = value;
  79584. },
  79585. enumerable: true,
  79586. configurable: true
  79587. });
  79588. ;
  79589. ;
  79590. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  79591. /**
  79592. * The camera exposure used on this material.
  79593. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  79594. * This corresponds to a photographic exposure.
  79595. */
  79596. get: function () {
  79597. return this._imageProcessingConfiguration.exposure;
  79598. },
  79599. /**
  79600. * The camera exposure used on this material.
  79601. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  79602. * This corresponds to a photographic exposure.
  79603. */
  79604. set: function (value) {
  79605. this._imageProcessingConfiguration.exposure = value;
  79606. },
  79607. enumerable: true,
  79608. configurable: true
  79609. });
  79610. ;
  79611. ;
  79612. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  79613. /**
  79614. * Gets The camera contrast used on this material.
  79615. */
  79616. get: function () {
  79617. return this._imageProcessingConfiguration.contrast;
  79618. },
  79619. /**
  79620. * Sets The camera contrast used on this material.
  79621. */
  79622. set: function (value) {
  79623. this._imageProcessingConfiguration.contrast = value;
  79624. },
  79625. enumerable: true,
  79626. configurable: true
  79627. });
  79628. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  79629. /**
  79630. * Gets the Color Grading 2D Lookup Texture.
  79631. */
  79632. get: function () {
  79633. return this._imageProcessingConfiguration.colorGradingTexture;
  79634. },
  79635. /**
  79636. * Sets the Color Grading 2D Lookup Texture.
  79637. */
  79638. set: function (value) {
  79639. this.imageProcessingConfiguration.colorGradingTexture = value;
  79640. },
  79641. enumerable: true,
  79642. configurable: true
  79643. });
  79644. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  79645. /**
  79646. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  79647. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  79648. * 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;
  79649. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  79650. */
  79651. get: function () {
  79652. return this.imageProcessingConfiguration.colorCurves;
  79653. },
  79654. /**
  79655. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  79656. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  79657. * 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;
  79658. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  79659. */
  79660. set: function (value) {
  79661. this.imageProcessingConfiguration.colorCurves = value;
  79662. },
  79663. enumerable: true,
  79664. configurable: true
  79665. });
  79666. /**
  79667. * The entire material has been created in order to prevent overdraw.
  79668. * @returns false
  79669. */
  79670. BackgroundMaterial.prototype.needAlphaTesting = function () {
  79671. return true;
  79672. };
  79673. /**
  79674. * The entire material has been created in order to prevent overdraw.
  79675. * @returns true if blending is enable
  79676. */
  79677. BackgroundMaterial.prototype.needAlphaBlending = function () {
  79678. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  79679. };
  79680. /**
  79681. * Checks wether the material is ready to be rendered for a given mesh.
  79682. * @param mesh The mesh to render
  79683. * @param subMesh The submesh to check against
  79684. * @param useInstances Specify wether or not the material is used with instances
  79685. */
  79686. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  79687. var _this = this;
  79688. if (useInstances === void 0) { useInstances = false; }
  79689. if (subMesh.effect && this.isFrozen) {
  79690. if (this._wasPreviouslyReady) {
  79691. return true;
  79692. }
  79693. }
  79694. if (!subMesh._materialDefines) {
  79695. subMesh._materialDefines = new BackgroundMaterialDefines();
  79696. }
  79697. var scene = this.getScene();
  79698. var defines = subMesh._materialDefines;
  79699. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  79700. if (defines._renderId === scene.getRenderId()) {
  79701. return true;
  79702. }
  79703. }
  79704. var engine = scene.getEngine();
  79705. // Lights
  79706. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  79707. defines._needNormals = true;
  79708. // Textures
  79709. if (defines._areTexturesDirty) {
  79710. defines._needUVs = false;
  79711. if (scene.texturesEnabled) {
  79712. if (scene.getEngine().getCaps().textureLOD) {
  79713. defines.TEXTURELODSUPPORT = true;
  79714. }
  79715. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  79716. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  79717. return false;
  79718. }
  79719. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  79720. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  79721. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  79722. defines.OPACITYFRESNEL = this._opacityFresnel;
  79723. }
  79724. else {
  79725. defines.DIFFUSE = false;
  79726. defines.DIFFUSEHASALPHA = false;
  79727. defines.GAMMADIFFUSE = false;
  79728. defines.OPACITYFRESNEL = false;
  79729. }
  79730. var reflectionTexture = this._reflectionTexture;
  79731. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  79732. if (!reflectionTexture.isReadyOrNotBlocking()) {
  79733. return false;
  79734. }
  79735. defines.REFLECTION = true;
  79736. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  79737. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  79738. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  79739. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  79740. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  79741. defines.INVERTCUBICMAP = true;
  79742. }
  79743. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  79744. switch (reflectionTexture.coordinatesMode) {
  79745. case BABYLON.Texture.CUBIC_MODE:
  79746. case BABYLON.Texture.INVCUBIC_MODE:
  79747. defines.REFLECTIONMAP_CUBIC = true;
  79748. break;
  79749. case BABYLON.Texture.EXPLICIT_MODE:
  79750. defines.REFLECTIONMAP_EXPLICIT = true;
  79751. break;
  79752. case BABYLON.Texture.PLANAR_MODE:
  79753. defines.REFLECTIONMAP_PLANAR = true;
  79754. break;
  79755. case BABYLON.Texture.PROJECTION_MODE:
  79756. defines.REFLECTIONMAP_PROJECTION = true;
  79757. break;
  79758. case BABYLON.Texture.SKYBOX_MODE:
  79759. defines.REFLECTIONMAP_SKYBOX = true;
  79760. break;
  79761. case BABYLON.Texture.SPHERICAL_MODE:
  79762. defines.REFLECTIONMAP_SPHERICAL = true;
  79763. break;
  79764. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  79765. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  79766. break;
  79767. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  79768. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  79769. break;
  79770. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  79771. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  79772. break;
  79773. }
  79774. if (this.reflectionFresnel) {
  79775. defines.REFLECTIONFRESNEL = true;
  79776. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  79777. this._reflectionControls.x = this.reflectionAmount;
  79778. this._reflectionControls.y = this.reflectionReflectance0;
  79779. this._reflectionControls.z = this.reflectionReflectance90;
  79780. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  79781. }
  79782. else {
  79783. defines.REFLECTIONFRESNEL = false;
  79784. defines.REFLECTIONFALLOFF = false;
  79785. }
  79786. }
  79787. else {
  79788. defines.REFLECTION = false;
  79789. defines.REFLECTIONFALLOFF = false;
  79790. defines.REFLECTIONBLUR = false;
  79791. defines.REFLECTIONMAP_3D = false;
  79792. defines.REFLECTIONMAP_SPHERICAL = false;
  79793. defines.REFLECTIONMAP_PLANAR = false;
  79794. defines.REFLECTIONMAP_CUBIC = false;
  79795. defines.REFLECTIONMAP_PROJECTION = false;
  79796. defines.REFLECTIONMAP_SKYBOX = false;
  79797. defines.REFLECTIONMAP_EXPLICIT = false;
  79798. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  79799. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  79800. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  79801. defines.INVERTCUBICMAP = false;
  79802. defines.REFLECTIONMAP_OPPOSITEZ = false;
  79803. defines.LODINREFLECTIONALPHA = false;
  79804. defines.GAMMAREFLECTION = false;
  79805. }
  79806. }
  79807. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  79808. defines.USERGBCOLOR = this._useRGBColor;
  79809. defines.NOISE = this._enableNoise;
  79810. }
  79811. if (defines._areImageProcessingDirty) {
  79812. if (!this._imageProcessingConfiguration.isReady()) {
  79813. return false;
  79814. }
  79815. this._imageProcessingConfiguration.prepareDefines(defines);
  79816. }
  79817. // Misc.
  79818. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, defines);
  79819. // Values that need to be evaluated on every frame
  79820. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances, false);
  79821. // Attribs
  79822. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  79823. if (mesh) {
  79824. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  79825. mesh.createNormals(true);
  79826. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  79827. }
  79828. }
  79829. }
  79830. // Get correct effect
  79831. if (defines.isDirty) {
  79832. defines.markAsProcessed();
  79833. scene.resetCachedMaterial();
  79834. // Fallbacks
  79835. var fallbacks = new BABYLON.EffectFallbacks();
  79836. if (defines.FOG) {
  79837. fallbacks.addFallback(0, "FOG");
  79838. }
  79839. if (defines.POINTSIZE) {
  79840. fallbacks.addFallback(1, "POINTSIZE");
  79841. }
  79842. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  79843. if (defines.NUM_BONE_INFLUENCERS > 0) {
  79844. fallbacks.addCPUSkinningFallback(0, mesh);
  79845. }
  79846. //Attributes
  79847. var attribs = [BABYLON.VertexBuffer.PositionKind];
  79848. if (defines.NORMAL) {
  79849. attribs.push(BABYLON.VertexBuffer.NormalKind);
  79850. }
  79851. if (defines.UV1) {
  79852. attribs.push(BABYLON.VertexBuffer.UVKind);
  79853. }
  79854. if (defines.UV2) {
  79855. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  79856. }
  79857. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  79858. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  79859. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  79860. "vFogInfos", "vFogColor", "pointSize",
  79861. "vClipPlane", "mBones",
  79862. "vPrimaryColor", "vSecondaryColor", "vTertiaryColor",
  79863. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos",
  79864. "shadowLevel", "alpha",
  79865. "vBackgroundCenter", "vReflectionControl",
  79866. "vDiffuseInfos", "diffuseMatrix",
  79867. ];
  79868. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  79869. var uniformBuffers = ["Material", "Scene"];
  79870. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  79871. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  79872. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  79873. uniformsNames: uniforms,
  79874. uniformBuffersNames: uniformBuffers,
  79875. samplers: samplers,
  79876. defines: defines,
  79877. maxSimultaneousLights: this._maxSimultaneousLights
  79878. });
  79879. var onCompiled = function (effect) {
  79880. if (_this.onCompiled) {
  79881. _this.onCompiled(effect);
  79882. }
  79883. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  79884. };
  79885. var join = defines.toString();
  79886. subMesh.setEffect(scene.getEngine().createEffect("background", {
  79887. attributes: attribs,
  79888. uniformsNames: uniforms,
  79889. uniformBuffersNames: uniformBuffers,
  79890. samplers: samplers,
  79891. defines: join,
  79892. fallbacks: fallbacks,
  79893. onCompiled: onCompiled,
  79894. onError: this.onError,
  79895. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  79896. }, engine), defines);
  79897. this.buildUniformLayout();
  79898. }
  79899. if (!subMesh.effect || !subMesh.effect.isReady()) {
  79900. return false;
  79901. }
  79902. defines._renderId = scene.getRenderId();
  79903. this._wasPreviouslyReady = true;
  79904. return true;
  79905. };
  79906. /**
  79907. * Build the uniform buffer used in the material.
  79908. */
  79909. BackgroundMaterial.prototype.buildUniformLayout = function () {
  79910. // Order is important !
  79911. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  79912. this._uniformBuffer.addUniform("vSecondaryColor", 4);
  79913. this._uniformBuffer.addUniform("vTertiaryColor", 4);
  79914. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  79915. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  79916. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  79917. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  79918. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  79919. this._uniformBuffer.addUniform("pointSize", 1);
  79920. this._uniformBuffer.addUniform("shadowLevel", 1);
  79921. this._uniformBuffer.addUniform("alpha", 1);
  79922. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  79923. this._uniformBuffer.addUniform("vReflectionControl", 4);
  79924. this._uniformBuffer.create();
  79925. };
  79926. /**
  79927. * Unbind the material.
  79928. */
  79929. BackgroundMaterial.prototype.unbind = function () {
  79930. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  79931. this._uniformBuffer.setTexture("diffuseSampler", null);
  79932. }
  79933. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  79934. this._uniformBuffer.setTexture("reflectionSampler", null);
  79935. }
  79936. _super.prototype.unbind.call(this);
  79937. };
  79938. /**
  79939. * Bind only the world matrix to the material.
  79940. * @param world The world matrix to bind.
  79941. */
  79942. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  79943. this._activeEffect.setMatrix("world", world);
  79944. };
  79945. /**
  79946. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  79947. * @param world The world matrix to bind.
  79948. * @param subMesh The submesh to bind for.
  79949. */
  79950. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  79951. var scene = this.getScene();
  79952. var defines = subMesh._materialDefines;
  79953. if (!defines) {
  79954. return;
  79955. }
  79956. var effect = subMesh.effect;
  79957. if (!effect) {
  79958. return;
  79959. }
  79960. this._activeEffect = effect;
  79961. // Matrices
  79962. this.bindOnlyWorldMatrix(world);
  79963. // Bones
  79964. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  79965. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  79966. if (mustRebind) {
  79967. this._uniformBuffer.bindToEffect(effect, "Material");
  79968. this.bindViewProjection(effect);
  79969. var reflectionTexture = this._reflectionTexture;
  79970. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  79971. // Texture uniforms
  79972. if (scene.texturesEnabled) {
  79973. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  79974. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  79975. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  79976. }
  79977. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  79978. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  79979. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  79980. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  79981. }
  79982. }
  79983. if (this.shadowLevel > 0) {
  79984. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  79985. }
  79986. this._uniformBuffer.updateFloat("alpha", this.alpha);
  79987. // Point size
  79988. if (this.pointsCloud) {
  79989. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  79990. }
  79991. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, this._primaryLevel);
  79992. this._uniformBuffer.updateColor4("vSecondaryColor", this._secondaryColor, this._secondaryLevel);
  79993. this._uniformBuffer.updateColor4("vTertiaryColor", this._tertiaryColor, this._tertiaryLevel);
  79994. }
  79995. // Textures
  79996. if (scene.texturesEnabled) {
  79997. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  79998. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  79999. }
  80000. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  80001. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  80002. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  80003. }
  80004. else if (!defines.REFLECTIONBLUR) {
  80005. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  80006. }
  80007. else {
  80008. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  80009. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  80010. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  80011. }
  80012. if (defines.REFLECTIONFRESNEL) {
  80013. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  80014. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  80015. }
  80016. }
  80017. }
  80018. // Clip plane
  80019. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  80020. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  80021. }
  80022. if (mustRebind || !this.isFrozen) {
  80023. if (scene.lightsEnabled) {
  80024. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  80025. }
  80026. // View
  80027. this.bindView(effect);
  80028. // Fog
  80029. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  80030. // image processing
  80031. this._imageProcessingConfiguration.bind(this._activeEffect);
  80032. }
  80033. this._uniformBuffer.update();
  80034. this._afterBind(mesh);
  80035. };
  80036. /**
  80037. * Dispose the material.
  80038. * @forceDisposeEffect Force disposal of the associated effect.
  80039. * @forceDisposeTextures Force disposal of the associated textures.
  80040. */
  80041. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  80042. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  80043. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  80044. if (forceDisposeTextures) {
  80045. if (this.diffuseTexture) {
  80046. this.diffuseTexture.dispose();
  80047. }
  80048. if (this.reflectionTexture) {
  80049. this.reflectionTexture.dispose();
  80050. }
  80051. }
  80052. this._renderTargets.dispose();
  80053. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  80054. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  80055. }
  80056. _super.prototype.dispose.call(this, forceDisposeEffect);
  80057. };
  80058. /**
  80059. * Clones the material.
  80060. * @name The cloned name.
  80061. * @returns The cloned material.
  80062. */
  80063. BackgroundMaterial.prototype.clone = function (name) {
  80064. var _this = this;
  80065. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  80066. };
  80067. /**
  80068. * Serializes the current material to its JSON representation.
  80069. * @returns The JSON representation.
  80070. */
  80071. BackgroundMaterial.prototype.serialize = function () {
  80072. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  80073. serializationObject.customType = "BABYLON.BackgroundMaterial";
  80074. return serializationObject;
  80075. };
  80076. /**
  80077. * Gets the class name of the material
  80078. * @returns "BackgroundMaterial"
  80079. */
  80080. BackgroundMaterial.prototype.getClassName = function () {
  80081. return "BackgroundMaterial";
  80082. };
  80083. /**
  80084. * Parse a JSON input to create back a background material.
  80085. * @param source
  80086. * @param scene
  80087. * @param rootUrl
  80088. * @returns the instantiated BackgroundMaterial.
  80089. */
  80090. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  80091. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  80092. };
  80093. /**
  80094. * Standard reflectance value at parallel view angle.
  80095. */
  80096. BackgroundMaterial.standardReflectance0 = 0.05;
  80097. /**
  80098. * Standard reflectance value at grazing angle.
  80099. */
  80100. BackgroundMaterial.standardReflectance90 = 0.5;
  80101. __decorate([
  80102. BABYLON.serializeAsColor3()
  80103. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  80104. __decorate([
  80105. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  80106. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  80107. __decorate([
  80108. BABYLON.serialize()
  80109. ], BackgroundMaterial.prototype, "_primaryLevel", void 0);
  80110. __decorate([
  80111. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  80112. ], BackgroundMaterial.prototype, "primaryLevel", void 0);
  80113. __decorate([
  80114. BABYLON.serializeAsColor3()
  80115. ], BackgroundMaterial.prototype, "_secondaryColor", void 0);
  80116. __decorate([
  80117. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  80118. ], BackgroundMaterial.prototype, "secondaryColor", void 0);
  80119. __decorate([
  80120. BABYLON.serialize()
  80121. ], BackgroundMaterial.prototype, "_secondaryLevel", void 0);
  80122. __decorate([
  80123. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  80124. ], BackgroundMaterial.prototype, "secondaryLevel", void 0);
  80125. __decorate([
  80126. BABYLON.serializeAsColor3()
  80127. ], BackgroundMaterial.prototype, "_tertiaryColor", void 0);
  80128. __decorate([
  80129. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  80130. ], BackgroundMaterial.prototype, "tertiaryColor", void 0);
  80131. __decorate([
  80132. BABYLON.serialize()
  80133. ], BackgroundMaterial.prototype, "_tertiaryLevel", void 0);
  80134. __decorate([
  80135. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  80136. ], BackgroundMaterial.prototype, "tertiaryLevel", void 0);
  80137. __decorate([
  80138. BABYLON.serializeAsTexture()
  80139. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  80140. __decorate([
  80141. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  80142. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  80143. __decorate([
  80144. BABYLON.serialize()
  80145. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  80146. __decorate([
  80147. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  80148. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  80149. __decorate([
  80150. BABYLON.serializeAsTexture()
  80151. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  80152. __decorate([
  80153. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  80154. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  80155. __decorate([
  80156. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  80157. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  80158. __decorate([
  80159. BABYLON.serialize()
  80160. ], BackgroundMaterial.prototype, "_shadowBlurScale", void 0);
  80161. __decorate([
  80162. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  80163. ], BackgroundMaterial.prototype, "shadowBlurScale", void 0);
  80164. __decorate([
  80165. BABYLON.serialize()
  80166. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  80167. __decorate([
  80168. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  80169. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  80170. __decorate([
  80171. BABYLON.serializeAsVector3()
  80172. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  80173. __decorate([
  80174. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  80175. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  80176. __decorate([
  80177. BABYLON.serialize()
  80178. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  80179. __decorate([
  80180. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  80181. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  80182. __decorate([
  80183. BABYLON.serialize()
  80184. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  80185. __decorate([
  80186. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  80187. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  80188. __decorate([
  80189. BABYLON.serialize()
  80190. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  80191. __decorate([
  80192. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  80193. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  80194. __decorate([
  80195. BABYLON.serialize()
  80196. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  80197. __decorate([
  80198. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  80199. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  80200. __decorate([
  80201. BABYLON.serialize()
  80202. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  80203. __decorate([
  80204. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  80205. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  80206. __decorate([
  80207. BABYLON.serialize()
  80208. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  80209. __decorate([
  80210. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  80211. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  80212. __decorate([
  80213. BABYLON.serialize()
  80214. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  80215. __decorate([
  80216. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  80217. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  80218. __decorate([
  80219. BABYLON.serialize()
  80220. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  80221. __decorate([
  80222. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  80223. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  80224. __decorate([
  80225. BABYLON.serialize()
  80226. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  80227. __decorate([
  80228. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  80229. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  80230. __decorate([
  80231. BABYLON.serializeAsImageProcessingConfiguration()
  80232. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  80233. return BackgroundMaterial;
  80234. }(BABYLON.PushMaterial));
  80235. BABYLON.BackgroundMaterial = BackgroundMaterial;
  80236. })(BABYLON || (BABYLON = {}));
  80237. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  80238. var __assign = (this && this.__assign) || Object.assign || function(t) {
  80239. for (var s, i = 1, n = arguments.length; i < n; i++) {
  80240. s = arguments[i];
  80241. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  80242. t[p] = s[p];
  80243. }
  80244. return t;
  80245. };
  80246. var BABYLON;
  80247. (function (BABYLON) {
  80248. /**
  80249. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  80250. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  80251. * It also helps with the default setup of your imageProcessing configuration.
  80252. */
  80253. var EnvironmentHelper = /** @class */ (function () {
  80254. /**
  80255. * constructor
  80256. * @param options
  80257. * @param scene The scene to add the material to
  80258. */
  80259. function EnvironmentHelper(options, scene) {
  80260. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  80261. this._scene = scene;
  80262. this._setupBackground();
  80263. this._setupImageProcessing();
  80264. }
  80265. /**
  80266. * Creates the default options for the helper.
  80267. */
  80268. EnvironmentHelper._getDefaultOptions = function () {
  80269. return {
  80270. createGround: true,
  80271. groundSize: 15,
  80272. groundTexture: this._groundTextureCDNUrl,
  80273. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  80274. groundOpacity: 0.9,
  80275. enableGroundShadow: true,
  80276. groundShadowLevel: 0.5,
  80277. enableGroundMirror: false,
  80278. groundMirrorSizeRatio: 0.3,
  80279. groundMirrorBlurKernel: 64,
  80280. groundMirrorAmount: 1,
  80281. groundMirrorFresnelWeight: 1,
  80282. groundMirrorFallOffDistance: 0,
  80283. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  80284. createSkybox: true,
  80285. skyboxSize: 20,
  80286. skyboxTexture: this._skyboxTextureCDNUrl,
  80287. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  80288. backgroundYRotation: 0,
  80289. sizeAuto: true,
  80290. rootPosition: BABYLON.Vector3.Zero(),
  80291. setupImageProcessing: true,
  80292. environmentTexture: this._environmentTextureCDNUrl,
  80293. cameraExposure: 0.8,
  80294. cameraContrast: 1.2,
  80295. toneMappingEnabled: true,
  80296. };
  80297. };
  80298. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  80299. /**
  80300. * Gets the root mesh created by the helper.
  80301. */
  80302. get: function () {
  80303. return this._rootMesh;
  80304. },
  80305. enumerable: true,
  80306. configurable: true
  80307. });
  80308. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  80309. /**
  80310. * Gets the skybox created by the helper.
  80311. */
  80312. get: function () {
  80313. return this._skybox;
  80314. },
  80315. enumerable: true,
  80316. configurable: true
  80317. });
  80318. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  80319. /**
  80320. * Gets the skybox texture created by the helper.
  80321. */
  80322. get: function () {
  80323. return this._skyboxTexture;
  80324. },
  80325. enumerable: true,
  80326. configurable: true
  80327. });
  80328. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  80329. /**
  80330. * Gets the skybox material created by the helper.
  80331. */
  80332. get: function () {
  80333. return this._skyboxMaterial;
  80334. },
  80335. enumerable: true,
  80336. configurable: true
  80337. });
  80338. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  80339. /**
  80340. * Gets the ground mesh created by the helper.
  80341. */
  80342. get: function () {
  80343. return this._ground;
  80344. },
  80345. enumerable: true,
  80346. configurable: true
  80347. });
  80348. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  80349. /**
  80350. * Gets the ground texture created by the helper.
  80351. */
  80352. get: function () {
  80353. return this._groundTexture;
  80354. },
  80355. enumerable: true,
  80356. configurable: true
  80357. });
  80358. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  80359. /**
  80360. * Gets the ground mirror created by the helper.
  80361. */
  80362. get: function () {
  80363. return this._groundMirror;
  80364. },
  80365. enumerable: true,
  80366. configurable: true
  80367. });
  80368. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  80369. /**
  80370. * Gets the ground mirror render list to helps pushing the meshes
  80371. * you wish in the ground reflection.
  80372. */
  80373. get: function () {
  80374. if (this._groundMirror) {
  80375. return this._groundMirror.renderList;
  80376. }
  80377. return null;
  80378. },
  80379. enumerable: true,
  80380. configurable: true
  80381. });
  80382. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  80383. /**
  80384. * Gets the ground material created by the helper.
  80385. */
  80386. get: function () {
  80387. return this._groundMaterial;
  80388. },
  80389. enumerable: true,
  80390. configurable: true
  80391. });
  80392. /**
  80393. * Updates the background according to the new options
  80394. * @param options
  80395. */
  80396. EnvironmentHelper.prototype.updateOptions = function (options) {
  80397. var newOptions = __assign({}, this._options, options);
  80398. if (this._ground && !newOptions.createGround) {
  80399. this._ground.dispose();
  80400. this._ground = null;
  80401. }
  80402. if (this._groundMaterial && !newOptions.createGround) {
  80403. this._groundMaterial.dispose();
  80404. this._groundMaterial = null;
  80405. }
  80406. if (this._groundTexture) {
  80407. if (this._options.groundTexture != newOptions.groundTexture) {
  80408. this._groundTexture.dispose();
  80409. this._groundTexture = null;
  80410. }
  80411. }
  80412. if (this._skybox && !newOptions.createSkybox) {
  80413. this._skybox.dispose();
  80414. this._skybox = null;
  80415. }
  80416. if (this._skyboxMaterial && !newOptions.createSkybox) {
  80417. this._skyboxMaterial.dispose();
  80418. this._skyboxMaterial = null;
  80419. }
  80420. if (this._skyboxTexture) {
  80421. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  80422. this._skyboxTexture.dispose();
  80423. this._skyboxTexture = null;
  80424. }
  80425. }
  80426. if (this._groundMirror && !newOptions.enableGroundMirror) {
  80427. this._groundMirror.dispose();
  80428. this._groundMirror = null;
  80429. }
  80430. if (this._scene.environmentTexture) {
  80431. if (this._options.environmentTexture != newOptions.environmentTexture) {
  80432. this._scene.environmentTexture.dispose();
  80433. }
  80434. }
  80435. this._options = newOptions;
  80436. this._setupBackground();
  80437. this._setupImageProcessing();
  80438. };
  80439. /**
  80440. * Sets the primary color of all the available elements.
  80441. * @param color
  80442. */
  80443. EnvironmentHelper.prototype.setMainColor = function (color) {
  80444. if (this.groundMaterial) {
  80445. this.groundMaterial.primaryColor = color;
  80446. }
  80447. if (this.skyboxMaterial) {
  80448. this.skyboxMaterial.primaryColor = color;
  80449. }
  80450. if (this.groundMirror) {
  80451. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  80452. }
  80453. };
  80454. /**
  80455. * Setup the image processing according to the specified options.
  80456. */
  80457. EnvironmentHelper.prototype._setupImageProcessing = function () {
  80458. if (this._options.setupImageProcessing) {
  80459. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  80460. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  80461. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  80462. this._setupEnvironmentTexture();
  80463. }
  80464. };
  80465. /**
  80466. * Setup the environment texture according to the specified options.
  80467. */
  80468. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  80469. if (this._scene.environmentTexture) {
  80470. return;
  80471. }
  80472. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  80473. this._scene.environmentTexture = this._options.environmentTexture;
  80474. return;
  80475. }
  80476. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  80477. this._scene.environmentTexture = environmentTexture;
  80478. };
  80479. /**
  80480. * Setup the background according to the specified options.
  80481. */
  80482. EnvironmentHelper.prototype._setupBackground = function () {
  80483. if (!this._rootMesh) {
  80484. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  80485. }
  80486. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  80487. var sceneSize = this._getSceneSize();
  80488. if (this._options.createGround) {
  80489. this._setupGround(sceneSize);
  80490. this._setupGroundMaterial();
  80491. this._setupGroundDiffuseTexture();
  80492. if (this._options.enableGroundMirror) {
  80493. this._setupGroundMirrorTexture(sceneSize);
  80494. }
  80495. this._setupMirrorInGroundMaterial();
  80496. }
  80497. if (this._options.createSkybox) {
  80498. this._setupSkybox(sceneSize);
  80499. this._setupSkyboxMaterial();
  80500. this._setupSkyboxReflectionTexture();
  80501. }
  80502. this._rootMesh.position.x = sceneSize.rootPosition.x;
  80503. this._rootMesh.position.z = sceneSize.rootPosition.z;
  80504. this._rootMesh.position.y = sceneSize.rootPosition.y;
  80505. };
  80506. /**
  80507. * Get the scene sizes according to the setup.
  80508. */
  80509. EnvironmentHelper.prototype._getSceneSize = function () {
  80510. var groundSize = this._options.groundSize;
  80511. var skyboxSize = this._options.skyboxSize;
  80512. var rootPosition = this._options.rootPosition;
  80513. if (!this._scene.meshes || this._scene.meshes.length === 1) {
  80514. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  80515. }
  80516. var sceneExtends = this._scene.getWorldExtends();
  80517. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  80518. var bias = 0.0001;
  80519. if (this._options.sizeAuto) {
  80520. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  80521. this._scene.activeCamera.upperRadiusLimit) {
  80522. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  80523. }
  80524. if (this._scene.activeCamera) {
  80525. bias = (this._scene.activeCamera.maxZ - this._scene.activeCamera.minZ) / 10000;
  80526. }
  80527. var sceneDiagonalLenght = sceneDiagonal.length();
  80528. if (sceneDiagonalLenght > groundSize) {
  80529. groundSize = sceneDiagonalLenght * 2;
  80530. }
  80531. // 10 % bigger.
  80532. groundSize *= 1.1;
  80533. skyboxSize *= 1.5;
  80534. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  80535. rootPosition.y = sceneExtends.min.y - bias;
  80536. }
  80537. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  80538. };
  80539. /**
  80540. * Setup the ground according to the specified options.
  80541. */
  80542. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  80543. var _this = this;
  80544. if (!this._ground) {
  80545. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  80546. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  80547. this._ground.parent = this._rootMesh;
  80548. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  80549. }
  80550. this._ground.receiveShadows = this._options.enableGroundShadow;
  80551. };
  80552. /**
  80553. * Setup the ground material according to the specified options.
  80554. */
  80555. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  80556. if (!this._groundMaterial) {
  80557. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  80558. }
  80559. this._groundMaterial.alpha = this._options.groundOpacity;
  80560. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  80561. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  80562. this._groundMaterial.primaryLevel = 1;
  80563. this._groundMaterial.primaryColor = this._options.groundColor;
  80564. this._groundMaterial.secondaryLevel = 0;
  80565. this._groundMaterial.tertiaryLevel = 0;
  80566. this._groundMaterial.useRGBColor = false;
  80567. this._groundMaterial.enableNoise = true;
  80568. if (this._ground) {
  80569. this._ground.material = this._groundMaterial;
  80570. }
  80571. };
  80572. /**
  80573. * Setup the ground diffuse texture according to the specified options.
  80574. */
  80575. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  80576. if (!this._groundMaterial) {
  80577. return;
  80578. }
  80579. if (this._groundTexture) {
  80580. return;
  80581. }
  80582. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  80583. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  80584. return;
  80585. }
  80586. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene);
  80587. diffuseTexture.gammaSpace = false;
  80588. diffuseTexture.hasAlpha = true;
  80589. this._groundMaterial.diffuseTexture = diffuseTexture;
  80590. };
  80591. /**
  80592. * Setup the ground mirror texture according to the specified options.
  80593. */
  80594. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  80595. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  80596. if (!this._groundMirror) {
  80597. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  80598. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  80599. this._groundMirror.anisotropicFilteringLevel = 1;
  80600. this._groundMirror.wrapU = wrapping;
  80601. this._groundMirror.wrapV = wrapping;
  80602. this._groundMirror.gammaSpace = false;
  80603. if (this._groundMirror.renderList) {
  80604. for (var i = 0; i < this._scene.meshes.length; i++) {
  80605. var mesh = this._scene.meshes[i];
  80606. if (mesh !== this._ground &&
  80607. mesh !== this._skybox &&
  80608. mesh !== this._rootMesh) {
  80609. this._groundMirror.renderList.push(mesh);
  80610. }
  80611. }
  80612. }
  80613. }
  80614. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  80615. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  80616. };
  80617. /**
  80618. * Setup the ground to receive the mirror texture.
  80619. */
  80620. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  80621. if (this._groundMaterial) {
  80622. this._groundMaterial.reflectionTexture = this._groundMirror;
  80623. this._groundMaterial.reflectionFresnel = true;
  80624. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  80625. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  80626. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  80627. }
  80628. };
  80629. /**
  80630. * Setup the skybox according to the specified options.
  80631. */
  80632. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  80633. var _this = this;
  80634. if (!this._skybox) {
  80635. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  80636. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  80637. }
  80638. this._skybox.parent = this._rootMesh;
  80639. };
  80640. /**
  80641. * Setup the skybox material according to the specified options.
  80642. */
  80643. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  80644. if (!this._skybox) {
  80645. return;
  80646. }
  80647. if (!this._skyboxMaterial) {
  80648. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  80649. }
  80650. this._skyboxMaterial.useRGBColor = false;
  80651. this._skyboxMaterial.primaryLevel = 1;
  80652. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  80653. this._skyboxMaterial.secondaryLevel = 0;
  80654. this._skyboxMaterial.tertiaryLevel = 0;
  80655. this._skyboxMaterial.enableNoise = true;
  80656. this._skybox.material = this._skyboxMaterial;
  80657. };
  80658. /**
  80659. * Setup the skybox reflection texture according to the specified options.
  80660. */
  80661. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  80662. if (!this._skyboxMaterial) {
  80663. return;
  80664. }
  80665. if (this._skyboxTexture) {
  80666. return;
  80667. }
  80668. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  80669. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  80670. return;
  80671. }
  80672. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene);
  80673. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  80674. this._skyboxTexture.gammaSpace = false;
  80675. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  80676. };
  80677. /**
  80678. * Dispose all the elements created by the Helper.
  80679. */
  80680. EnvironmentHelper.prototype.dispose = function () {
  80681. if (this._groundMaterial) {
  80682. this._groundMaterial.dispose(true, true);
  80683. }
  80684. if (this._skyboxMaterial) {
  80685. this._skyboxMaterial.dispose(true, true);
  80686. }
  80687. this._rootMesh.dispose(false);
  80688. };
  80689. /**
  80690. * Default ground texture URL.
  80691. */
  80692. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  80693. /**
  80694. * Default skybox texture URL.
  80695. */
  80696. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  80697. /**
  80698. * Default environment texture URL.
  80699. */
  80700. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  80701. return EnvironmentHelper;
  80702. }());
  80703. BABYLON.EnvironmentHelper = EnvironmentHelper;
  80704. })(BABYLON || (BABYLON = {}));
  80705. //# sourceMappingURL=babylon.environmentHelper.js.map
  80706. 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=abs(texture2D(textureSampler,vUV).r);\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,1.0);\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=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}","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#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 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}","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);\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\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\nbaseColor.a=abs(offset-baseColor.a);\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\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#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\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}"};
  80707. 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#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}\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 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#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;\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":"vec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvec3 direction=normalize(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\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#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#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 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 PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCoord{X}))*KERNEL_WEIGHT{X};\n#else\nblend+=texture2D(textureSampler,sampleCoord{X})*KERNEL_WEIGHT{X};\n#endif","kernelBlurFragment2":"#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*KERNEL_DEP_WEIGHT{X};\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*KERNEL_DEP_WEIGHT{X};\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;\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 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};"};
  80708. (function universalModuleDefinition(root, factory) {
  80709. var f = factory();
  80710. if (root && root["BABYLON"]) {
  80711. return;
  80712. }
  80713. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  80714. globalObject["BABYLON"] = f;
  80715. if(typeof exports === 'object' && typeof module === 'object')
  80716. module.exports = f;
  80717. else if(typeof define === 'function' && define.amd)
  80718. define(["BABYLON"], factory);
  80719. else if(typeof exports === 'object')
  80720. exports["BABYLON"] = f;
  80721. else {
  80722. root["BABYLON"] = f;
  80723. }
  80724. })(this, function() {
  80725. return BABYLON;
  80726. });